Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loops

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])
}
like image 634
Matt Bannert Avatar asked Feb 19 '23 12:02

Matt Bannert


1 Answers

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)
like image 50
csgillespie Avatar answered Feb 21 '23 15:02

csgillespie