Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

r - Match vectors by pattern

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...