Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...