grepl模式长度警告

时间:2018-04-09 00:10:43

标签: r dplyr

我在data.frame x中有两列名为" preferred_cat"和" var_nm"。我想创建一个名为" preferred_tag"的第三列。值为1或0。

1-如果preferred_cat(对于前qq)是var_nm的子集(对于ex jdsajqq)或
0-如果preferred_cat(对于前qq)不是var_nm的子集(对于ex qdsajq)

x <- x %>% mutate(preferred_tag=ifelse(grepl(preferred_cat,var_nm,fixed=TRUE),1,0))

但是我收到了这个警告:

Warning message:
In grepl(preferred_cat, var_nm, fixed = TRUE) :
  argument 'pattern' has length > 1 and only the first element will be used

这个警告意味着什么,我该如何避免呢?

1 个答案:

答案 0 :(得分:0)

grepl不会采用字符串向量。您可以使用map2

中的purrr

首先创建一个新函数,如果有子字符串则返回1,否则返回0.

new_func <- function(x,y){
if(grepl(x,y,fixed=TRUE)){
  check <- 1
} else{
  check <- 0
}
check
}

现在map2这个函数对每对字符串:

library(purrr)
x <- x %>% 
     mutate(preferred_tag=map2(referred_cat, var_nm, new_func))