R基于条件的名称组顺序

R基于条件的名称组顺序,r,R,我试图将组名按顺序排列,同时让其他名称的位置取决于上面提到的顺序 假设我有以下的名字 a <- c("zz", "CountryA", "CountryC", "xy", "aa","CountryB") 我从下面的函数中得到了上面的结果 orderGroup <- function(regex,char) { ### purpose ## order by group leaving the rest unchanged group <- grep(re

我试图将组名按顺序排列,同时让其他名称的位置取决于上面提到的顺序

假设我有以下的名字

 a <- c("zz", "CountryA", "CountryC", "xy", "aa","CountryB")
我从下面的函数中得到了上面的结果

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)]])
 }
从这一点上,我有一个问题:

  • 你有更好的方法吗。除了上面提到的,我还没有测试过这个函数,所以我确信还有一些情况需要添加和调整
    • 这似乎有效:

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

      不过,它与OP的功能没有本质区别。

      。编辑,示例,希望它能让想法更清晰。ThanksYours更紧凑,更容易掌握。我以前没有使用过append函数。我会记住的谢谢。@Frank Nice one(+1)。但是,最好在=之后指定
      。我只是在读了描述后才注意到。@akrun同意,谢谢。是的,每当我猜到如何通过position传递到
      append
      ,我就错了,认为这就像
      append(x,position,y)
      orderGroup("Country",a)
      
      patt = "^Country"
      
      cs = grep(patt, a)
      append(a[-cs], sort(a[cs]), after = cs[1]-1)
      # "zz"       "CountryA" "CountryB" "CountryC" "xy"       "aa"