user3720887 user3720887 - 1 year ago 102
R Question

filter or subset list by partial object name in R

I have a list with 417 data frames in it. Each data frame has a separate name in the list beginning with "Dec 1981" and ending with "Aug 2016". The objects are in chronological order.

I would like to subset or filter this list just by month name. For example, create a new list object with just the Jan objects(data frames). The name of my list is

and I've attempted a few different solution so far. None of which work.

Jan_data <- SST_list[names(SST_list)=="Jan"]

That returns nothing, but is to be expected. I have attempted some code with grep and grepl, but those crash my R session.

I also tried

Jan_data <- lapply(SST_list, "[","Jan")

but no luck there.

This seems like it should be a simple task, but I'm having quite a bit of trouble.

Answer Source

We can use grep to match the "Jan" substring in the names of 'SST_list'

SST_list[grep("Jan", names(SST_list))]  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download