I have a dataframe with 3840 rows (only one value in columnA). I would like to convert this into a dataframe (40 rows & 96 columns). I tried to use the following code.
a1<-a[1:40,]
a2<-cbind(a1,a[41:80,])
a3<-cbind(a2,a[81:120,])
a4<-cbind(a3,a[121:160,])
a5<-cbind(a4,a[161:200,])
a6<-cbind(a5,a[201:240,])
......
a96<-cbind(a95,a[3801:3840,])
This is too tedious work. Can I use either while loop if loop? If anyone can help me, it will be a great. Thanks.
Just redim
`dim<-`(a[,1],c(40,96))
and you are done (wrap with as.data.frame
as desired)
我们可以使用matrix
matrix(a[,1], nrow=40, ncol=96)
You could do this with data.table
like so (noting that this has the advantage that it is easily extended to handle the case when a
has two or many columns that you'd like to reshape):
library(data.table) #1.9.7 +
setDT(a)[, ct := 1:40]
dcast(a, rowid(ct) ~ ct, value.var = "columnA")
(instructions for installing the development version, which has the rowid
function, here )
Test data:
set.seed(10932)
a <- data.table(columnA = rnorm(3840))
If you're feeling parsimonious, here's a one-line version:
dcast(a, rowid(ct <<- rep_len(1:40, nrow(a))) ~ ct, value.var = "columnA")
And another (this viable in reshape2
and the current CRAN version of data.table
):
dcast(a, rep(1:ceiling((nrow(a) / 40)), each = 40, length.out = nrow(a)) ~
rep_len(1:40, nrow(a)), value.var = "columnA")
Here's a base R method:
# Fake data
dat = data.frame(v1 = rnorm(3840))
# Split into columns of 40 rows each
dat.new = as.data.frame(mapply(function(i,j) {dat[i:j,]},
which(1:nrow(dat) %% 40 == 1), which(1:nrow(dat) %% 40 == 0)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.