首页 > 解决方案 > R regexp 用于对 char 向量进行奇数排序

问题描述

我有数百个文件需要以复杂的方式对其列进行排序。想象一个字符向量x,它是names(foo)where foois a的结果data.frame

x <- c("x1","i2","Component.1","Component.10","Component.143","Component.13",
       "r4","A","C16:1n-7")

我想根据以下规则对其进行排序:首先,以“组件”开头的任何内容都按字母顺序排列。其次,以“C”和数字开头的任何剩余内容按字母顺序排列。第三个按字母顺序剩余的东西。

因为x那将是:

x[c(3,4,6,5,9,8,2,7,1)]

这是regexp一种任务吗?一个人用match吗?每个文件将具有不同数量的列(因此x将具有不同的长度)。任何提示表示赞赏。

标签: rregexsorting

解决方案


您可以使用以下功能order来实现base-r

x <- c("x1","i2","Component.1","Component.10","Component.143","Component.13",
       "r4","A","C16:1n-7")    
order(
    !startsWith(x, "Component"), # 0 - starts with component, 1 - o.w.
    !grepl("^C\\d", x),          # 0 - starts with C<NUMBER>, 1 - o.w.
    x                            # alphabetical
)
# output: 3 4 6 5 9 8 2 7 1

推荐阅读