【问题标题】:Paste some elements of mixed vector粘贴混合矢量的一些元素
【发布时间】:2016-11-16 18:31:54
【问题描述】:

我有一个向量,其中的术语可能后跟零个或多个以“/”开头的限定符。第一个元素应该始终是一个术语。

 mesh <- c("Animals", "/physiology" , "/metabolism*", 
           "Insects", "Arabidopsis", "/immunology" )

我想用最后一个词加入限定符,得到一个新向量

Animals/physiology
Animals/metabolism*
Insects
Arabidopsis/immunology

【问题讨论】:

    标签: r ncbi


    【解决方案1】:

    通过grepling 为以/ 开头的值创建组标识符,在此组标识符上拆分,然后paste0

    unlist(by(mesh, cumsum(grepl("^[^/]",mesh)), FUN=function(x) paste0(x[1], x[-1])))
    #                      11                       12                        2                        3 
    #    "Animals/physiology"    "Animals/metabolism*"                "Insects" "Arabidopsis/immunology"
    

    【讨论】:

      【解决方案2】:

      另一个选项是tapply

       unlist(tapply(mesh, cumsum(grepl("^[^/]", mesh)), 
                 FUN = function(x) paste0(x[1], x[-1])), use.names=FALSE)
       #[1] "Animals/physiology"     "Animals/metabolism*"    "Insects"                "Arabidopsis/immunology"
      

      【讨论】:

        【解决方案3】:

        能想到比这更优雅的东西:

        mesh <- c("Animals", "/physiology" , "/metabolism*", 
               "Insects", "Arabidopsis", "/immunology" )
        
        #gets "prefixes", assuming they all start with a letter:
        pre <- grep(pattern = "^[[:alpha:]]", x = mesh) 
        
        #gives integer IDs for the prefix-suffix groupings
        id <- rep(1:length(pre), times = diff(c(pre,length(mesh) + 1)))
        
        #function that pastes the first term in vector to any remaining ones 
             #will just return first term if there are no others
        combine <- function(x) paste0(x[1], x[-1])
        
        #groups mesh by id, then applies combine to each group
        results <- tapply(mesh, INDEX = id, FUN = combine)
        
        unlist(results)
        

        【讨论】:

          猜你喜欢
          • 2021-07-27
          • 2019-11-07
          • 2021-02-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-11-27
          相关资源
          最近更新 更多