Matt Bannert
Matt Bannert

Reputation: 28274

add elements of a vector to elements of a list in R

I have a simple list and a simple vector of the same length. I would like to add the ith element of the vector to the ith element of the list. Is there a way to do better than with this for loop?

test <- list(element1=list(a=1,b=2,a1=8),
             element2=list(a=9,d=17))
vec <- c(12,25)

for (i in 1:length(test)){
    test[[i]] <- c(test[[i]],vec[i])
}

Upvotes: 4

Views: 1944

Answers (2)

Wojciech Sobala
Wojciech Sobala

Reputation: 7561

You can allways translate for loop into lapply/apply/sapply. Here is example for your code.

"for"(i, 1:length(test), test[i] <- c(test[[i]], vec[i]))

test <- lapply(1:length(test), function(i) c(test[[i]], vec[i]))

Upvotes: 1

csgillespie
csgillespie

Reputation: 60522

Use the multivariate equivalent of sapply, i.e. mapply. In the code below, the function c is applied to the first elements of each test and vec, then the second elements, etc...

test = mapply(c, test, vec)

Upvotes: 7

Related Questions