Search code examples
rlistconditional-statementscharactertransform

R transform character vectors in a list, conditional on the content of the vector


The problem is I have a list of character vectors.

example:

mylist <- list( c("once","upon","a","time"),
                c("once", "in", "olden", "times"),
                c("Let","all","good","men"),
                c("Let","This"),
                c("once", "is","never","enough"),
                c("in","the"),
                c("Come","dance","all","around"))

and I want to prepend c("one", "two") to those vectors starting "once" to end up with the list

mylist <- list( c("one", "two", "once","upon","a","time"),
                c("one", "two", "once", "in", "olden", "times"),
                c("Let","all","good","men"),
                c("Let","This"),
                c("one", "two", "once", "is","never","enough"),
                c("in","the"),
                c("Come","dance","all","around"))

so far

I can select the relevant vectors

mylist[grep("once",mylist)]

and I can prepend "one" and "two" to create a results list

resultlist <- lapply(mylist[grep("once",mylist)],FUN = function(listrow) prepend(listrow,c("One","Two")))

But putting the results in the correct place in mylist?

Nope, that escapes me!

Hints, tips and solutions most welcome :-)


Solution

  • I don't think you need grep at all. Loop over the list, checking the first value for "once" and appending via c() the extra values:

    lapply(mylist, \(x) if(x[1] == "once") c("one", "two", x) else x)
    ##[[1]]
    ##[1] "one"  "two"  "once" "upon" "a"    "time"
    ##
    ##[[2]]
    ##[1] "one"   "two"   "once"  "in"    "olden" "times"
    ##
    ##[[3]]
    ##[1] "Let"  "all"  "good" "men" 
    ##
    ##[[4]]
    ##[1] "Let"  "This"
    ##
    ##[[5]]
    ##[1] "one"    "two"    "once"   "is"     "never"  "enough"
    ##
    ##[[6]]
    ##[1] "in"  "the"
    ##
    ##[[7]]
    ##[1] "Come"   "dance"  "all"    "around"