问题
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 tibble
s
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