【发布时间】:2021-01-31 01:45:46
【问题描述】:
我有一个数据框列表,需要转置数据框中的每一列并创建一个新的数据框。这是一个可重现的例子。所以我需要通过为列表中的每个数据框转置 4 列来创建 4 个大小为 500 行和 100 列的数据框。
# simulate list of 500 dataframes where each dataframe has 100 rows and 4 columns
mat<-as.matrix(diag(c(1,2,3,4)))
dat<-list()
for (i in 1:500){
dat[[i]]<-as.data.frame(mvrnorm(100,rep(0,4),mat))
}
# I need an output that would look something like this - transpose first column in each of the 500
dataframes and combine into a single dataframe. I am showing for 3 dataframes in a list.
t(dat[[1]][,1])
t(dat[[2]][,1])
t(dat[[3]][,1])
dat.1<-rbind(t(dat[[1]][,1]),t(dat[[2]][,1]),t(dat[[3]][,1]))
head(dat.1)
# Tried doing this function for transposing first column of each of the 500 dataframes in the list
# but gives an error that "dim(X) must have positive length ".
dat.1<-apply(dat,1,function(x){t(dat[[x]][,1])})
【问题讨论】:
标签: r