Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort a dataframe based on a specific column in R with dplyr

I have a dataframe that looks like this

df <- data.frame(time=seq(1,4,1),col1=c("a","b","d","c"), col2=c("d","a","c","b"))
df
#>   time col1 col2
#> 1    1    a    d
#> 2    2    b    a
#> 3    3    d    c
#> 4    4    c    b

Created on 2021-11-06 by the reprex package (v2.0.1)

I want to sort my data frame based on col2 and look like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  time col1 col2 
    3    d    d
    1    a    a
    4    c    c
    2    b    b

Any ideas or help is highly appreciated!

>Solution :

Don’t know, if this makes any sense, but you could do a self join:

library(tidyr)
library(dplyr)

df %>% 
  select(col2) %>% 
  inner_join(df %>% mutate(col2 = col1), by = "col2") %>% 
  select(time, col1, col2)

This returns

  time col1 col2
1    3    d    d
2    1    a    a
3    4    c    c
4    2    b    b
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading