Matt Bannert
Matt Bannert

Reputation: 28264

Indexing list of data.frames – how to get all x-th columns?

I have list of data.frames and I wonder whether there is an easy indexing way of getting all third columns of all data.frames. Or all columns named x? Speaking R:

lapply(names(mylist),function(x) mylist[[x]][,3])

Is there any way to do it by just indexing, like mylist[[]][,3]? (which does not work obviously)

EDIT: And how do you do that, when you want to use a function like nlevels in that, like

  lapply(names(mylist),function(x) nlevels(mylist[[x]][,3]))

given that column 3 is a factor.

Upvotes: 9

Views: 7384

Answers (1)

kohske
kohske

Reputation: 66842

Maybe this is somewhat easier:

lapply(mylist, "[[", 3)
lapply(mylist, "[[", name_of_column)

Upvotes: 12

Related Questions