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

Asked 1 month ago
Viewed 12 times

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 :-)

##### gonzalo_dickens
asked 1 month ago

• We can use
``````lapply(mylist , \(x) if(grepl("once" , x))
append(x,  c("one", "two") , 0) else x)
``````
• Output
``````[]
 "one"  "two"  "once" "upon" "a"    "time"

[]
 "one"   "two"   "once"  "in"    "olden" "times"

[]
 "Let"  "all"  "good" "men"

[]
 "Let"  "This"

[]
 "one"    "two"    "once"   "is"     "never"  "enough"

[]
 "in"  "the"

[]
 "Come"   "dance"  "all"    "around"
``````
##### polly_kuphal26
answered 1 month ago

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 == "once") c("one", "two", x) else x)
##[]
## "one"  "two"  "once" "upon" "a"    "time"
##
##[]
## "one"   "two"   "once"  "in"    "olden" "times"
##
##[]
## "Let"  "all"  "good" "men"
##
##[]
## "Let"  "This"
##
##[]
## "one"    "two"    "once"   "is"     "never"  "enough"
##
##[]
## "in"  "the"
##
##[]
## "Come"   "dance"  "all"    "around"
``````
##### stantondeckow
answered 1 month ago