get column from list of dataframes R
Asked Answered
F

2

12

I am an R beginner and I am stuck on this problem. I had a dataframe and by using the split() function I have created a list of dataframes, e.g:

dfList <- split(mtcars, mtcars$cyl)

Now I want to retrieve a column of a specific dataframe, e.g. column 2 from dataframe 1, so something like

dfList[1][2]

What I can do right now is create for loops to get inside the data structure. But I can't find a oneliner to do it, if it exists. How can I do that?

Facture answered 3/2, 2015 at 18:2 Comment(3)
Try lapply(dfList, '[[', 2). If you need it as a matrix sapply(dfList, '[[',2)Ovoid
Perhaps you want to use dfList[[1]][2]? Here's an example for you to test: lst <- split(mtcats, mtcars$cyl) and then lst[[1]][2].Holly
lapply(dfList, '[[', 2) wowza R syntax really is the worstStereo
P
15

I'm putting docendo's comment here to close out the question.

If you want to extract an element from a list (and treat it like a data.frame) rather than subset a list (to create a smaller list), you need to use the [[ ]] syntax. Plus, to get a column by index from a data.frame, you either need to use [[ idx ]] or [, idx ]. These are pretty basic indexing operations that you will probably want to review if you will be programming in R. So your "correct" call is probably

dfList[[1]][[2]]
Princess answered 4/2, 2015 at 6:27 Comment(0)
V
0

You can use pluck to extract, which will take a combination of names and indices:

library(purrr)

pluck(dfList, 1, "cyl")
Van answered 31/5, 2024 at 22:22 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.