0

I have vectors x and type

x <- c("value", "class", "value2", "value3", "class2", "other")
type <- c("value", "class")

and like to match x to type based on type patterns.
E.g. with grepl("^value", x) I get a logical vector of matching patterns for the element "value" in type. Using some function of the apply family helps to generalize, but how to match this to x?

Hope what I'd like to achieve is comprehensible, my desired result in this small example is

c("value", "class", "value", "value", "class")

One Note: I prefer a base r solution over tidyverse!

oguz ismail
  • 1
  • 16
  • 47
  • 69
Thomas
  • 1,252
  • 6
  • 24
  • Related [grep using a character vector with multiple patterns](https://stackoverflow.com/questions/7597559/grep-using-a-character-vector-with-multiple-patterns) – markus Jan 12 '21 at 16:14

2 Answers2

1

One base R solution using grep would be to build a regex alternation using your type vector:

regex <- paste0(type, collapse="|")
x[grep(regex, x)]

[1] "value"  "class"  "value2" "value3" "class2"

Data:

x <- c("value", "class", "value2", "value3", "class2", "other")
type <- c("value", "class")

Note: I have deliberately added a non matching item "other" to the x vector to show that grep does not pick up on it using your target pattern.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Works really nice though I'd like to return the matched types, not the values of `x` that can be assigned. – Thomas Jan 12 '21 at 16:25
1

How about using nested sapply:

sapply(x,function(x)type[sapply(type,function(y)grepl(paste0("^",y),x))])
  value   class  value2  value3  class2 
"value" "class" "value" "value" "class" 

Or if you have unmatched classes:

sapply(x,function(x){z <- type[sapply(type,function(y)grepl(paste0("^",y),x))]; ifelse(length(z) > 0, z, NA)})
  value   class  value2  value3  class2   other 
"value" "class" "value" "value" "class"      NA 
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
  • Could you add `simplify=TRUE` to the outer `sapply`? Otherwise it returns a list in case I have some unmatched type in `x`. I think it then just works – Thomas Jan 12 '21 at 16:30
  • `simplify = TRUE` is the default. Maybe we can add an `ifelse` – Ian Campbell Jan 12 '21 at 16:34