David Gladson
David Gladson

Reputation: 557

How to arrange the strings in my data frame given below in a desired order in R?

I have a data frame where the elements in one of the columns are

"1.cn3.ap.1"
"7.fr9.ap.3"
"4.dl.ap.2"
"5.d2.cr.1"
"4.dl.u.1"
"4.dl.ap.1"

df<- df[order(df$A),]

#this gave the following result :
"1.cn3.ap.1"
"4.dl.ap.1"
"4.dl.ap.2"
"4.dl.u.1"
"5.d2.cr.1" 
"7.fr9.ap.3"   

But I need my data in this manner:

"1.cn3.ap.1"
"4.dl.u.1"
"4.dl.ap.1"
"4.dl.ap.2"
"5.d2.cr.1" 
"7.fr9.ap.3"

Upvotes: 1

Views: 119

Answers (1)

Matt Jewett
Matt Jewett

Reputation: 3369

You may be able to get what you need by splitting the data by the period, and sorting on the individual columns, then bringing the columns together again after sorting. something similar to this maybe?

library(dplyr)
library(tidyr)

df <- df %>% 
      separate(A, into = c("part1","part2","part3","part4"), sep = "\\.") %>% 
      arrange(part1, part2, desc(part3), part4) %>% 
      unite(A, part1:part4, sep = ".")

Upvotes: 1

Related Questions