Jonathan H Jonathan H - 11 months ago 40
R Question

R retrieving values from inside a data frame in a list

I have a list with several data frames in it:

weekday <- c("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
data1 <- c(letters[1:7])
data2 <- c(letters[8:14])

df1 <- data.frame(day = weekday, val = data1)
df2 <- data.frame(day = weekday, val = data2)

my_list <- list(list_1 = df1, list_2 = df2)

I'm trying to figure out how to pull the data that matches a specific day in a specific data frame. I know how to extract the data frame

> my_list[["list_1"]]
day val
1 Sun a
2 Mon b
3 Tue c
4 Wed d
5 Thu e
6 Fri f
7 Sat g

And how to extract a specific row when I know the index of the day:

> my_list[["list_1"]][1,]
day val
1 Sun a

But I can't for the life of me figure out how to get a specific row when I want to match a value. An example of what I think should work is:

my_list[["list_1"]][list_1$day == "Sun",]

but I get the error:

Error in `[.data.frame`(my_list[["list_1"]], list_1$day == "Sun", ) :
object 'list_1' not found

I know I could just subset the df to a temporary variable and then it would be easy, I'm just trying to make this compact and follow good practices.

Answer Source

Try my_list$list_1$day == "Sun". Your my_list is essentially a nested list (since a data frame is also a list), so you can chain the $ operator to get all the way down to the columns. So your code could be

my_list$list_1[my_list$list_1$day == "Sun", ]

As you can see, that code is not an easy read. For this reason, I like with(). This is handy here since a list can be coerced to an environment, and it is a lot easier to read.

with(my_list, list_1[list_1$day == "Sun", ])