在列中按字母顺序对字符进行排序?

时间:2018-10-11 09:18:32

标签: r string tidyverse

我目前有以下专栏:

Themes
toast,eggs,fruit
chocolate,eggs,milk
fruit,apple,milk

所以此列有3行,我希望进行以下操作

Themes 
eggs,fruit,toast
chocolate,eggs,milk
apple,fruit,milk 

要对所有行中的所有值进行按字母顺序排序吗?

我该如何实现?我的行比这多得多,我想根据需要保留逗号-我知道使用strinr但不确定如何

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

最明显的方法是用逗号分割字符串,sort将其粘贴然后粘贴回去。

df$Themes <- sapply(strsplit(df$Themes, ","), function(x) 
                              paste0(sort(x), collapse = ","))


df
#               Themes
#1    eggs,fruit,toast
#2 chocolate,eggs,milk
#3    apple,fruit,milk

tidyverse使用相同的逻辑

library(tidyverse)

df %>%
  rowwise() %>%
  mutate(Themes = str_c(str_sort(str_split(Themes, ",",simplify = TRUE)),
                                                        collapse = ","))

#  Themes             
#  <chr>              
#1 eggs,fruit,toast   
#2 chocolate,eggs,milk
#3 apple,fruit,milk   

数据

df <- structure(list(Themes = c("toast,eggs,fruit", "chocolate,eggs,milk", 
 "fruit,apple,milk")), .Names = "Themes", row.names = c(NA, -3L
 ), class = "data.frame")