Create a list for each pattern of grep

Hellow i have the following df and pattern

df <- data.frame(class=c(5,8,10,15),student=c("US_NORTH","US_SOUTH","UK_EAST","BRAZIL"))
pattern <- c("US","UK")

I would identify US and UK students without using a loop.
The US student should be together in a list and the UK students in sublist as shown below:

target <- list(US=c(5,8),UK=10)

I know a loop could be used but i would like to have a vector solution.
Thanks

Here is one solution.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(purrr)
df <- data.frame(class=c(5,8,10,15),student=c("US_NORTH","US_SOUTH","UK_EAST","BRAZIL"))
pattern <- c("US","UK")
MyFunc <- function(KEY){
  tmp <- filter(df,grepl(KEY,x = student))
  tmp$class
}
target <- map(pattern,MyFunc)
names(target) <- pattern
target
#> $US
#> [1] 5 8
#> 
#> $UK
#> [1] 10

Created on 2021-11-08 by the reprex package (v2.0.1)

Thank a lot.
It works.
But do you have a native R solution?
My program should work on any laptop, even for those who have problems with package installation.

You can rewrite my solution by replacing the filter function with subsetting of df using square brackets, e.g. df[grepl(),]. You can replace the map function with lapply.

1 Like