R 拆分一个数据帧并创建多个数据帧或列表
在拆分矩阵后,我想同时从一个dataframe创建一个列表或多个data.frame。我正在使用combn函数创建一个矩阵。 例如:R 拆分一个数据帧并创建多个数据帧或列表,r,split,combn,R,Split,Combn,在拆分矩阵后,我想同时从一个dataframe创建一个列表或多个data.frame。我正在使用combn函数创建一个矩阵。 例如: combos<-combn(1:3, 2) combos [,1] [,2] [,3] [1,] 1 1 2 [2,] 2 3 3 此后,, 我希望将这些数据帧或列表与其他数据帧或列表合并以获
combos<-combn(1:3, 2)
combos
[,1] [,2] [,3]
[1,] 1 1 2
[2,] 2 3 3
此后,,
我希望将这些数据帧或列表与其他数据帧或列表合并以获得以下结果:
使用此新数据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
col1实际上,您可以使用lappy
在列表上循环
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
combos实际上,您可以使用lappy
在列表上循环
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
comboscombn(1:3,2,FUN=函数(x)rbind(df[,x]),setNames(dfo,names(df[,x])),simplify=FALSE)
(假设您想这样组合数字和字母)谢谢user20650。我在邮件上错了。信件只是一个例子。我想把数字和数字结合起来,(dfo也是数字)。对不起,我是我的第一篇帖子!在此编辑过程中未损坏任何矩阵。combn(1:3,2,FUN=函数(x)rbind(df[,x],setNames(dfo,names(df[,x])),simplify=FALSE)
(假设您想将数字和字母这样组合起来)感谢user20650。我在邮件上错了。信件只是一个例子。我想把数字和数字结合起来,(dfo也是数字)。对不起,我是我的第一篇帖子!在此编辑过程中未损坏任何矩阵。
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