Search code examples
rncbi

Paste some elements of mixed vector


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

Solution

  • 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"