Jacob
Jacob

Reputation: 41

Add a character to each vector in a list of vectors in R

I have a list of character vectors:

vector.list <- list("cytidine", "uridine", "dihydrouridine", "2'-O-methylcytidine")

I want to add a the character "30" to each vector in this list, resulting in:

vector.list
[[1]]
[1] "30"       "cytidine"

[[2]]
[1] "30"      "uridine"

[[3]]
[1] "30"             "dihydrouridine"

[[4]]
[1] "30"                  "2'-O-methylcytidine

I know how to do this with a "for loop" or by writing a function and using lapply. For example:

for (i in 1:length(vector.list)){
vector.list[[i]] <- c("30", vector.list[[i]])
}

However, I need to do this for many combinations of vector lists and characters and I want this code to be accessible to other people. I was wondering if there was a more elegant command for adding a character to each vector in a list of vectors in R?

Upvotes: 1

Views: 453

Answers (2)

Alexlok
Alexlok

Reputation: 3134

lapply(vector.list,
       function(x) c("30", x))

Upvotes: 1

G5W
G5W

Reputation: 37661

lapply(vector.list, append, "30", after=0)

Upvotes: 2

Related Questions