首页 > 解决方案 > 在列中按字母顺序对每个字符串进行排序

问题描述

如何按字母顺序对列中的每个单独的字符串进行排序?例如,下面是最佳输出的样子:

> x
      Current Age        Want
1 FrankGeorge  25 aeefggknorr
2    BobHenry  29    bbehnory
3 MichaelJohn  30 acehhijlmno

我只希望每个单独的单元格按字母顺序排序。我已经看到了R: Sort a string of items 按字母顺序How to change the order of words with letters order 中的响应,不幸的是它们没有达到我的目标。

标签: rstring

解决方案


我们可以用 拆分“当前”列,strsplit循环遍历listwithsapply和ed 字符pastesort

sapply(strsplit(tolower(x$Current), ""), function(x) paste(sort(x), collapse=""))
#[1] "aeefggknorr" "bbehnory"    "acehhijlmno"

数据

x <- structure(list(Current = c("FrankGeorge", "BobHenry", "MichaelJohn"
), Age = c(25L, 29L, 30L), Want = c("aeefggknorr", "bbehnory", 
"acehhijlmno")), class = "data.frame", row.names = c("1", "2", 
"3"))

推荐阅读