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])
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With