首页 > 解决方案 > 使用 dplyr 从其他数据帧创建一个新数据帧

问题描述

我有这 3 个数据框:

    df.1<-as.data.frame(matrix(rnorm(10),250,149))
    df.2<-as.data.frame(matrix(rnorm(10),250,149))
    df.3<-as.data.frame(matrix(rnorm(10),250,149))

我想用这些条件创建另一个数据框:

the columns 1,4,7,10,...445 of df.4... will be the columns from df.1

the columns 2,5,8,11,...446 of df.4... will be the columns from df.2

the columns 3,6,9,12,...447 of df.4... will be the columns from df.3

最后,我的 df.4 将有3*149列。

如何使用dplyr包及其功能做到这一点?

最重要的是,我怎样才能维护我的列名???

标签: rdplyr

解决方案


为此,我们将数据帧与bind_cols()然后重新排序组合select()如下:

library (dplyr)
df.4 <- bind_cols(df.1, df.2, df.3)
# create the column order 
order <- c()
for(i in 1:149){
    temp <- c(i, i+149, i+298)
    order <- c(order, temp)
}
df.4 <- df.4 %>% select(order)

这里使用的循环是循环数字 1:149 并且无论数据大小如何都不会很慢


推荐阅读