Convert columns in a list to a data frame in R
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 ?
2 answers

Here is one option with
tidyverse
, where wetranspose
the object to alist
of 'X1's and 'Y1s' separately and then bind the columns within inmap
to create alist
oftibble
slibrary(tidyverse) out < transpose(lst) %>% map(bind_cols)
It is better to keep it in a
list
, but if we want separate objectsoutx < out[[1]] outy < out[[2]] dim(outx) #[1] 10 100 dim(outy) #[1] 10 100
Or do an extraction with
lapply
frombase R
data.frame(lapply(lst, `[`, 'X1')) data.frame(lapply(lst, `[`, 'Y1'))

Using
do.call
cbind
, concat them into one dataframe , then we split the dataframe to get the expected out puts=do.call("cbind", lst) Y=s[,seq(2,200,2)] X=s[,seq(1,200,2)]