How can I cbind() sets of data frames in a loop to generate multiple data sets

孤街浪徒 提交于 2019-12-12 14:07:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!