拆分数据框并创建许多数据框或列表

时间:2016-03-27 21:35:32

标签: r split combn

我想在分割矩阵后同时从数据框创建一个列表或多个data.frame。我正在使用函数combn来创建一个矩阵。 例如:

 combos<-combn(1:3, 2)
 combos
 [,1] [,2] [,3]
 [1,]    1    1    2
 [2,]    2    3    3                                                            

我有一个包含3列的数据框。

col1<-c(0,2,4);col2<-c(1,3,5);col3<-c(6,7,8)
df<-cbind.data.frame(col1,col2,col3)
df
      col1 col2 col3
 1    0    1    6
 2    2    3    7
 3    4    5    8 

使用组合我想在数据框或列表中得到这个结果:

 df1
      col1 col2
 1    0    1  
 2    2    3  
 3    4    5  
df2
      col1  col3
 1    0      6
 2    2      7
 3    4      8 
df3
      col2 col3
 1     1    6
 2     3    7
 3     5    8    

之后, 我想将这些数据框或列表与其他数据框或列表一起加入以获得此结果: 使用这个新数据dfo

 col1<-c('a','c'); col2<-c('b','d')
 dfo<-cbind.data.frame(col1,col2)
      col1 col2
 1    a    b
 2    c    d

 df1o
      col1 col2
 1    0    1  
 2    2    3  
 3    4    5
 4    a    b
 5    c    d  

 df2o
      col1  col3
 1    0      6
 2    2      7
 3    4      8 
 4    a      b
 5    c      d

 df3o
      col2 col3
  1     1    6
  2     3    7
  3     5    8 
  4     a    b
  5     c    d 

我有3000 df和5000 dfo

1 个答案:

答案 0 :(得分:0)

实际上,您可以使用lapply循环遍历列表。

combos <- combn(1:3, 2)

col1 <- c(0,2,4); col2 <- c(1,3,5); col3 <- c(6,7,8)
df <- cbind.data.frame(col1,col2,col3)

df.1 <- lapply(1:ncol(combos), function(i){df[, combos[,i]]})

col1 <- c('a','c'); col2 <- c('b','d')
dfo <- cbind.data.frame(col1,col2)

dfo.1 <- lapply(df.1, function(x){
  names(dfo) <- names(x)
  return(rbind(x, dfo))
})
# [[1]]
#   col1 col2
# 1    0    1
# 2    2    3
# 3    4    5
# 4    a    b
# 5    c    d
# 
# [[2]]
#   col1 col3
# 1    0    6
# 2    2    7
# 3    4    8
# 4    a    b
# 5    c    d
# 
# [[3]]
#   col2 col3
# 1    1    6
# 2    3    7
# 3    5    8
# 4    a    b
# 5    c    d
相关问题