Sorting a dataframe by names in a column

Hi,

This is an example dataframe

Col 1 Col 2 Col 3 Col 4 Col 5

Apple Dog 1 2 5
Banana Elephant 3 4 6
Cat Apple 7 8 9
Dog Cat 10 11 12
Elephant Banana 13 14 15

Values given in column 3,4 and 5 represent values associated with names given in column 2. I find to sort my data frame such that the values in columns 2, 3, 4 and 5 correspond to names in column 1. This would mean

Col 1 Col 2 Col 3 Col 4 Col 5

Apple Apple 7 8 9
Banana Banana 13 14 15
Cat Cat 10 11 12
Dog Dog 1 2 5
Elephant Elephant 3 4 6

Can someone please help with an R code that would help me accomplish this? Many thanks

library(dplyr)

sample_df <- data.frame(
  stringsAsFactors = FALSE,
             Col_1 = c("Apple", "Banana", "Cat", "Dog", "Elephant"),
             Col_2 = c("Dog", "Elephant", "Apple", "Cat", "Banana"),
             Col_3 = c(1, 3, 7, 10, 13),
             Col_4 = c(2, 4, 8, 11, 14),
             Col_5 = c(5, 6, 9, 12, 15)
)

sample_df %>% 
    select(Col_1) %>% 
    left_join(sample_df %>% select(-Col_1), by = c("Col_1" = "Col_2")) %>% 
    mutate(Col_2 = Col_1) %>% 
    select(Col_1, Col_2, everything())
#>      Col_1    Col_2 Col_3 Col_4 Col_5
#> 1    Apple    Apple     7     8     9
#> 2   Banana   Banana    13    14    15
#> 3      Cat      Cat    10    11    12
#> 4      Dog      Dog     1     2     5
#> 5 Elephant Elephant     3     4     6

Created on 2021-05-09 by the reprex package (v2.0.0)

Note: Next time please provide a proper REPRoducible EXample (reprex) illustrating your issue.

Thanks a lot! This was very helpful!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.