I have a list of dataframes lsD
and a list of vectors lsV
. The length of the vectors is identical to the numbers of rows in the dataframes (in the toy example = 5).
I would like to add the vectors as an additional column to each dataframe. I got it to work with a for
loop, but my general question is: how can iterate through two lists by name without for
? Is there a lapply
way to do this?
Here is a toy example and my solution using the for
loop:
lsV <- list(x = sample(LETTERS[1:5], 5,replace=T),
y = sample(LETTERS[1:5], 5, replace=T),
z=sample(LETTERS[1:5], 5, replace=T))
lsD <- list(x = data.frame(matrix(sample(LETTERS[1:5], 20,replace=T), ncol=4)),
y = data.frame(matrix(sample(LETTERS[1:5], 20,replace=T), ncol=4)),
z = data.frame(matrix(sample(LETTERS[1:5], 20,replace=T), ncol=4)))
for (i in 1:length(lsV)) {lsD[[i]]<-cbind(lsD[[i]], lsV[[i]])}
Any ideas? I tried with the following, but of course it didn't work. Thanks!
lapply(names(lsD), function(X) {lsD$X<-cbind(lsD$X, lsV$X)})
The Map
function would be useful here
Map(cbind, lsD, Z=lsV)
Both Map
and mapply
are apply-style functions that accept multiple parameters and iterate over them simultaneously.
And
lapply(names(lsD), function(X) {lsD$X<-cbind(lsD$X, lsV$X)})
will never work because you can't use variable names with the '$' operator. You can use
lapply(names(lsD), function(X) {lsD[[X]]<-cbind(lsD[[X]], lsV[[X]])})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.