Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k 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 Reply

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...