Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select list element by name pattern in R

Tags:

regex

list

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

like image 395
Archymedes Avatar asked Feb 04 '23 22:02

Archymedes


1 Answers

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))
like image 62
akrun Avatar answered Feb 08 '23 16:02

akrun