Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

r - 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))

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


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".

In general, use gl(ncol(Mydata) / n, n) for "every n columns" (n must divide ncol(Mydata)).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...