问题
I have let say 4 data sets f1,f2,i1,i2
. I want to cbind()
f1
with i1
and f2
with i2
.
I can use
v1<-cbind(f1,i1)
v2<-cbind(f2,i2)
but I want to do this in some sort of loop.
I know the question is very basic. But after lots of searching I am still unable to find a solution for this.
回答1:
We can use Map
to cbind
the corresponding columns of both datasets
lst <- setNames(Map(cbind, mget(ls(pattern = "^f\\d+")),
mget(ls(pattern = "^i\\d+"))), paste0("v", seq_along(f1)))
to create a list
of datasets.
data
f1 <- data.frame(col1 = 1:5, col2 = 6:10)
f2 <- data.frame(col1 = 1:10, col2 = 11:20)
i1 <- data.frame(col3 = 11:15, col4 = 16:20)
i2 <- data.frame(col3 = 21:30, col4 = 31:40)
回答2:
This is more simplistic:
Map(cbind,list(f1,f2),list(i1,i2))
This code should work
来源:https://stackoverflow.com/questions/46054180/how-can-i-cbind-sets-of-data-frames-in-a-loop-to-generate-multiple-data-sets