Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select a specific columns in R nested list

suppose i have a list of data frames, just like this:

M1 <- data.frame(matrix(1:4, nrow = 2, ncol = 2))
M2 <- data.frame(matrix(1:9, nrow = 3, ncol = 3))
M3 <- data.frame(matrix(1:4, nrow = 2, ncol = 2))

mlist <- list(M1, M2, M3)

and now i want to select X1 columns from all of dataframes, I tried :

M.X1 <- mlist$X1

but failed with NULL:

> mlist$X1
NULL

I don't want to use for to extract each data frames' X1, is there some better way to do this ? And what if extract columns X3 ? (which means some columns may not exists in other row)

like image 646
jjdblast Avatar asked Sep 11 '25 16:09

jjdblast


1 Answers

Normally you can use lapply as below:

lapply(mlist, function(x) x$X2)

The 2nd parameter you define a function right inside to pass to each member of mlist.

like image 175
suhao399 Avatar answered Sep 13 '25 06:09

suhao399