简体   繁体   English

R根据条件对名称进行排序

[英]R Order group of names based on condition

I'm trying to put group names together order them, while letting the position of the other names depends on the order mentioned above above. 我试图将组名放在一起对它们进行排序,同时让其他名称的位置取决于上面提到的顺序。

Let's say I have the following names 假设我有以下名字

 a <- c("zz", "CountryA", "CountryC", "xy", "aa","CountryB")

and I want to order the Country together to give the following output. 我想订购该国家/地区以提供以下输出。

c("zz", "CountryA", "CountryB", "CountryC", "xy", "aa")

I got the results above from the following function. 我从下面的函数得到上面的结果。

orderGroup <- function(regex,char) {
### purpose
     ## order by group leaving the rest unchanged
    group <- grep(regex,char,value=TRUE)
    orderGroup <- group[order(group)]

    indexGroup <-  grep(regex,char)
    indexNotInGroup <-  grep(paste0("^[^",regex,"]"),char)

    c(char[indexNotInGroup[indexNotInGroup<min(indexGroup)]],
      orderGroup,char[indexNotInGroup[indexNotInGroup>min(orderc)]])
 }

usage: 用法:

orderGroup("Country",a)

From this point I have 1 question: 从这一点来说,我有1个问题:

  • Do you have a better way of doing this. 您有更好的方法吗? I have not tested the function except on the above so I'm sure there are cases to add and some tuning to do. 除上述功能外,我没有测试过该功能,因此我确定需要添加一些情况并进行一些调整。

This seems to work: 这似乎可行:

patt = "^Country"

cs = grep(patt, a)
append(a[-cs], sort(a[cs]), after = cs[1]-1)
# "zz"       "CountryA" "CountryB" "CountryC" "xy"       "aa" 

It is not substantially different from the OP's function, though. 但是,它与OP的功能没有实质性的不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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