[英]R program: list in one column -> data-frame with dimension
I have a dataframe with 3840 rows (only one value in columnA). 我有一个3840行的数据框(columnA中只有一个值)。 I would like to convert this into a dataframe (40 rows & 96 columns). 我想将其转换为数据框(40行和96列)。 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? 我可以使用while循环吗? 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) 并且您完成了(根据需要用as.data.frame
包装)
我们可以使用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): 您可以像这样用data.table
来做到这一点(注意,这样做的优点是可以很容易地扩展它以处理当a
有两个或多个要重塑的列的情况):
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 ) (有关安装具有rowid
功能的开发版本的说明,请rowid
此处 )
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
): 还有另一个(在reshape2
和reshape2
的当前CRAN版本中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: 这是基本的R方法:
# 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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.