r - 将两个 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)
但是,给我一个“未定义的列选择错误”。
解决方案
没有可重复的例子就不清楚。根据描述,我们可以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))
推荐阅读
- mysql - EntityFramework groupby 不能像在 mysql 上那样工作
- spring - 如何在春季使用 kotlin 将 @Value 定义为可为空?
- reactjs - Firebase 多种管理员类型
- python - 在 Anaconda 中创建多个 Jupyter 工作目录/配置文件
- c++ - VisualC – 在未导出的标头中实现的 DLL 类
- xslt - 根据孙子(带限定符)对完整节点进行排序
- php - 如果值与函数匹配,我如何从下拉列表中选择值?
- python - 我想在 django 的 view_project.html 页面中显示用户输入的所有数据
- makefile - 使用 Makefile 中的模式自定义目标
- angular - [(ngModel)]='products.title' 问题 // 类型 '{}' 上不存在属性 'title'