[英]transpose a columns to row in a list of dataframes and write it to a new dataframe in R
我有一个数据框列表,需要转置 dataframe 中的每一列并创建一个新的 dataframe。 这是一个可重现的例子。 因此,我需要通过为列表中的每个 dataframe 转置 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])})
我认为这就是你想要的:
do.call(rbind, lapply(dat, `[`, , 1L))
你可以试试:
result <- do.call(rbind,lapply(dat, `[[`, 1))
在tidyverse
中,我们可以使用
library(dplyr)
library(purrr)
map_dfr(dat, `[`, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.