Paste some elements of mixed vector

走远了吗. 提交于 2019-12-11 04:38:13

问题


I have a vector with terms that may be followed by zero or more qualifiers starting with "/". The first element should always be a term.

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

I'd like to join the qualifier with the last term and get a new vector

Animals/physiology
Animals/metabolism*
Insects
Arabidopsis/immunology

回答1:


Make a group identifier by grepling for values not starting with a /, split on this group identifier, then 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:


Another option is 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:


Can think of anything more elegant than this:

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)


来源:https://stackoverflow.com/questions/38364060/paste-some-elements-of-mixed-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!