lolo
lolo

Reputation: 646

Sort strings in a data frame in R

How can I sort in an ascending way the elements of a column inside a data frame?

For example, I have:

table<-data.frame(col1=c("w d f", "g t y", "c d a", "o w q"))

   col1
   w d f
   g t y
   c d a
   o w q

and I want

   col1
   d f w
   g t y
   a d c
   o q w

Upvotes: 0

Views: 467

Answers (2)

Monica Puerto
Monica Puerto

Reputation: 11

sort_c <- function(x){
  strsplit(as.character(x),"") %>% unlist() %>% sort() %>% str_c(collapse="")
}

apply(table,1,sort_social_q) %>% as.data.frame()

output: 1 dfw 2 gty 3 acd 4 oqw

Upvotes: 0

akrun
akrun

Reputation: 887128

We split the 'col1' by space into a list, sort the elements by looping through the elements (sapply) and paste it together

table$col1 <- sapply(strsplit(as.character(table$col1), ' '), 
                        function(x) paste(sort(x), collapse=' '))
table$col1
#[1] "d f w" "g t y" "a c d" "o q w"

Upvotes: 1

Related Questions