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!
$ 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 $.
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 “[[ ]]”.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With