Archymedes
Archymedes

Reputation: 441

Select list element by name pattern in R

I have a list like

places <- list(
  'cities-1' = c('Madrid', 'Valencia', 'Barcelona'),
  'countries-1' = c('España', 'Portugal', 'Francia'),
  'cities-2' = c('Alicante', 'San Sebastian', 'Lugo'),
  'countries-2' = c('Italia', 'Grecia', 'Alemania')
)

I would like to create a new list with those elements which their name accomplish the pattern 'cities'. If it would be possible, I would like use 'tidyverse' style.

Any help would be appreciated. Regards

Upvotes: 12

Views: 10764

Answers (1)

akrun
akrun

Reputation: 887501

It is easier with grep from base R. Get a logical index with grepl by checking the pattern 'cities' on the names of the list and then use that to subset the list elements

places[grepl("cities", names(places))]

or with tidyverse, instead of grepl, use str_detect (from stringr) and keep (from purrr) the list elements that satisfy the condition

library(tidyverse)
names(places) %>% 
      str_detect('cities') %>%
      keep(places, .)

As @Frank mentioned in the comments, a tbl or data.frame may be more convenient for analysis

data_frame(nm = names(places), places) %>% 
     unnest %>% 
     filter(str_detect(nm, "cities"))

Or in base R

subset(stack(places), grepl("cities", ind))

Upvotes: 16

Related Questions