我如何在列之间划分数据帧,例如在第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?
推荐答案
要拆分 Mydata
每4列。我们可以显式使用 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".
通常,使用 gl(ncol(Mydata)/ n,n)
表示每n列( n
必须除以 ncol(Mydata)
)。
In general, use gl(ncol(Mydata) / n, n)
for "every n columns" (n
must divide ncol(Mydata)
).
这篇关于我如何在列之间划分数据帧,例如在第n列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!