如何在列之间拆分数据框,例如在每第 n 列? [英] How do I split a data frame among columns, say at every nth column?
问题描述
假设我正在使用以下数据框:
Let's say I am working with the following data frame:
Mydata <- data.frame(X1 = c(1,2,3,4,5,6,7,8,9,10),X2 = c(1,3,1,1,1,5,1,1,8,1),
X3 = c(1,2,3,4,5,6,7,8,9,10),X4 = c(1,3,1,1,1,5,1,1,8,1),
X5 = c(1,2,3,4,5,6,7,8,9,10),X6 = c(1,3,1,1,1,5,1,1,8,1),
X7 = c(1,2,3,4,5,6,7,8,9,10),X8 = c(1,3,1,1,1,5,1,1,8,1),
X9 = c(1,2,3,4,5,6,7,8,9,10),X10 = c(1,3,1,1,1,5,1,1,8,1),
X11 = c(1,2,3,4,5,6,7,8,9,10),X12 = c(1,3,1,1,1,5,1,1,8,1))
我想将此数据帧拆分为三个独立的数据帧,其中 X1 ~ X4 列在一个数据框中,X5 ~ X8 在第二个数据框中,X9 ~ X12 列.我将如何编码以在任意数量的列中继续这种模式?
I want to split this data frame into three separate data frames, with columns X1 ~ X4 in one data frame, X5 ~ X8 in the second, and X9 ~ X12. How would I code this to continue this pattern for any number of columns?
推荐答案
每 4 列拆分 Mydata
.我们可以显式使用 use split.default
:
To split Mydata
every 4 columns. We can use explicitly use split.default
:
split.default(Mydata, rep(1:3, each = 4))
默认"方法可以按列拆分数据框.只需根据需要设置分组变量即可.
The "default" method can split a data frame by columns. Just set the grouping variable by your need.
对于平衡分组,gl
很方便(参见 ?gl
).我们可以使用gl(3, 4)
代替上面的rep(1:3, 4)
,这样可以避免从整数"到因子"的类型转换.
For balanced grouping, gl
is handy (see ?gl
). We can use gl(3, 4)
instead of rep(1:3, 4)
in the above, which avoids type conversion from "integer" to "factor".
一般来说,对于每n列"使用gl(ncol(Mydata)/n, n)
(n
必须除以ncol(Mydata)
).
In general, use gl(ncol(Mydata) / n, n)
for "every n columns" (n
must divide ncol(Mydata)
).
这篇关于如何在列之间拆分数据框,例如在每第 n 列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!