首页 > 解决方案 > 将两个 data.frames 合并为两列

问题描述

我有一个巨大的data.frame,我想重新排序。想法是将其分成两半(因为前半部分包含与后半部分不同的信息)并创建第三个数据框,它将是两者的组合。因为我总是需要第一个数据帧的前两列,然后是第二个数据帧的前两列,所以我需要帮助。

new1<-all_cont_video_algo[,1:826]
new2<-all_cont_video_algo[,827:length(all_cont_video_algo)]
df3<-data.frame()

新的数据框应如下所示:

新3[新1[1],新1[2],新2[1],新2[2],新1[3],新1[4],新2[3],新2[4],新1[5],新1[6 ]、new2[5]、new2[6] 等]。

伪算法,从数据框 new1 中 cbind 2 列,然后从数据框 new2 中 cbind 2 列,等等。

我现在尝试了以下方法(感谢 Akrun):

new1<-all_cont_video_algo[,1:826]
new2<-all_cont_video_algo[,827:length(all_cont_video_algo)]

new1<-as.data.frame(new1, stringsAsFactors =FALSE)
new2<-as.data.frame(new2, stringsAsFactors =FALSE)

df3<-data.frame()
f1 <- function(Ncol, n) {
as.integer(gl(Ncol, n, Ncol))
}  
lst1 <- split.default(new1, f1(ncol(new1), 2))
lst2 <- split.default(new2, f1(ncol(new2), 2))

lst3 <- Map(function(x, y) df3[unlist(cbind(x, y))], lst1, lst2)

但是,给我一个“未定义的列选择错误”。

标签: r

解决方案


没有可重复的例子就不清楚。根据描述,我们可以split将数据集列分成一个list数据集并使用Map对应cbind数据集的列,unlist并使用它来排序第三个数据集

1)创建一个函数来返回一个分组列用于分割数据集

f1 <- function(Ncol, n) {
 as.integer(gl(Ncol, n, Ncol))
  } 

2)将数据集拆分为列表

lst1 <- split.default(df1, f1(ncol(df1), 2))
lst2 <- split.default(df2, f1(ncol(df2), 2))

3)Map通过相应的list元素,cbind并将unlist其用于subset'df3'的列

lst3 <- Map(function(x, y) df3[unlist(cbind(x, y))], lst1, lst2)

数据

df1 <- as.data.frame(matrix(letters[1:10], 2, 5), stringsAsFactors = FALSE)
df2 <- as.data.frame(matrix(1:10, 2, 5))

推荐阅读