简体   繁体   中英

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("wdf", "gty", "cda", "owq"))

   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

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"
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM