Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get column from list of dataframes R

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? Thanks in advance!

like image 256
lightRW Avatar asked Feb 03 '15 18:02

lightRW


People also ask

How do you extract a column from a Dataframe in a list in R?

$ operator in R is used to extract a specific part of data or access a variable in a dataset. We can pass data frame column to a list by using $ operator. The columns to be selected are to be passed with dataframe name separated by $.

How do you access a Dataframe inside a list in R?

To access the top-level components of a list of data frames we have to use a double slicing operator “[[ ]]” which is two square brackets and if we want to access the lower or inner level components of a list we have to use another square bracket “[ ]” along with the double slicing operator “[[ ]]”.


1 Answers

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]]
like image 77
MrFlick Avatar answered Oct 15 '22 03:10

MrFlick