How to Apply the unique() Function in R (2 Examples)
In this post, I’ll illustrate how to remove duplicates from vectors and data frames using the unique function in R.
Example 1: Creating Vector with Unique Elements
my_x <- LETTERS[c(4, 1, 4, 3, 1, 4, 7, 1)] # Exemplifying vector my_x # Returning example vector # "D" "A" "D" "C" "A" "D" "G" "A" |
my_x <- LETTERS[c(4, 1, 4, 3, 1, 4, 7, 1)] # Exemplifying vector my_x # Returning example vector # "D" "A" "D" "C" "A" "D" "G" "A"
my_x_updated <- unique(my_x) # Applying unique function my_x_updated # Returning vector after applying unique() # "D" "A" "C" "G" |
my_x_updated <- unique(my_x) # Applying unique function my_x_updated # Returning vector after applying unique() # "D" "A" "C" "G"
Example 2: Creating Data Frame with Unique Rows
my_df <- data.frame(col1 = c("A", "B", "A", "C", "A"), # Exemplifying data frame col2 = c(222, 111, 222, 111, 111), col3 = 1) my_df # Returning example data frame # col1 col2 col3 # 1 A 222 1 # 2 B 111 1 # 3 A 222 1 # 4 C 111 1 # 5 A 111 1 |
my_df <- data.frame(col1 = c("A", "B", "A", "C", "A"), # Exemplifying data frame col2 = c(222, 111, 222, 111, 111), col3 = 1) my_df # Returning example data frame # col1 col2 col3 # 1 A 222 1 # 2 B 111 1 # 3 A 222 1 # 4 C 111 1 # 5 A 111 1
my_df_updated <- unique(my_df) # Applying unique function my_df_updated # Returning data frame after applying unique() # col1 col2 col3 # 1 A 222 1 # 2 B 111 1 # 4 C 111 1 # 5 A 111 1 |
my_df_updated <- unique(my_df) # Applying unique function my_df_updated # Returning data frame after applying unique() # col1 col2 col3 # 1 A 222 1 # 2 B 111 1 # 4 C 111 1 # 5 A 111 1