Convert columns in a list to a data frame in R

◇◆丶佛笑我妖孽 提交于 2019-12-12 18:05:17

问题


I have the following list that created using R,

set.seed(326581)
X1=rnorm(10,0,1)
Y1=rnorm(10,0,2)
data=data.frame(X1,Y1)

lst <- replicate(
  100,
  df.smpl <- data %>% sample_n(10, replace = T),
  simplify = FALSE)

this list represents 100 samples where each sample has 2 columns (X,Y) with a sample size of 10.

I need to separate all the X columns into one data frame and Y columns into one data frame. So finally i should have 2 data frames each have 100 columns and 10 rows.

I tried this loop ,

new1=c()
new2=c()
for(i in 1:100)
{
  new1[i]=lst[[i]]$X
  new2[i]=lst[[i]]$Y
}

But it is not working. Can anyone tell me to figure out the error ?


回答1:


Here is one option with tidyverse, where we transpose the object to a list of 'X1's and 'Y1s' separately and then bind the columns within in map to create a list of tibbles

library(tidyverse)
out <- transpose(lst) %>% 
              map(bind_cols)

It is better to keep it in a list, but if we want separate objects

outx <- out[[1]]
outy <- out[[2]]
dim(outx)
#[1]  10 100
dim(outy)
#[1]  10 100

Or do an extraction with lapply from base R

data.frame(lapply(lst, `[`, 'X1'))
data.frame(lapply(lst, `[`, 'Y1'))



回答2:


Using do.call cbind, concat them into one dataframe , then we split the dataframe to get the expected out put

s=do.call("cbind", lst)
Y=s[,seq(2,200,2)]
X=s[,seq(1,200,2)]


来源:https://stackoverflow.com/questions/51276653/convert-columns-in-a-list-to-a-data-frame-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!