拆分数据框并创建多个数据框或列表
split a dataframe and create many data frames or list
我想在拆分矩阵后同时从数据帧创建一个或多个列表 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
实际上,您可以使用 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
我想在拆分矩阵后同时从数据帧创建一个或多个列表 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
实际上,您可以使用 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