问题
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 grepl
ing 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