Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the same column for all data frames inside a list

Tags:

list

dataframe

r

I have an object like this:

d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
d3 <- data.frame(y1=c(7,8,9),y2=c(5,2,6))
my.list <- list(d1, d2, d3)
names(my.list) <- c("d1","d2","d3")

Is there a way to access the column y2 of all data frames inside the list once?

Something like this:

my.list[["d1"]]$y2

But this only works for one data frame at a time

like image 964
tss28 Avatar asked Dec 24 '22 23:12

tss28


1 Answers

Try

lapply(my.list, '[[', 'y2')

Or use sapply to get the output as a matrix

sapply(my.list, `[[`, 'y2')
like image 84
akrun Avatar answered Feb 13 '23 03:02

akrun