搜索不同列中的匹配行

时间:2018-03-22 07:28:12

标签: r function dplyr

我正在寻找能够在列和输出之间找到匹配项的函数,如果找到匹配的行输出"has matches""no matches"

例如

df = data.frame(id=c("good","bad","ugly","dirty","clean","frenzy"),di=c(1,2,"good","dirty",4,"ugly"))

> df
      id    di
1   good     1
2    bad     2
3   ugly  good
4  dirty dirty
5  clean     4
6 frenzy  ugly

我想在di列中检查id列是否匹配,以便

 > df
          id    di  match
    1   good     1  no matches
    2    bad     2  no matches
    3   ugly  good  has matches
    4  dirty dirty  has matches
    5  clean     4  no matches
    6 frenzy  ugly  has matches

我正在寻找的这种方法

match_func <- function(x,y){

  }

df%>%
  do(match_func(.$id,.$di))

提前致谢!

2 个答案:

答案 0 :(得分:4)

使用base R而不使用if/else语句,您可以使用以下代码计算match列。

df$match <- c("no matches", "has matches")[(df$di %in% df$id) + 1]
df
#      id    di       match
#1   good     1  no matches
#2    bad     2  no matches
#3   ugly  good has matches
#4  dirty dirty has matches
#5  clean     4  no matches
#6 frenzy  ugly has matches

答案 1 :(得分:3)

只需将%in%ifelse

一起使用即可
df %>% 
   mutate(match = ifelse(di %in% id, "has matches", "no matches"))

case_when

df %>% 
   mutate(match = case_when(di %in% id ~ "has matches",
                                   TRUE ~ "no matches"))

这可以直接包含在一个函数中。假设我们传递了不带引号的名称,然后使用enquo将其转换为quosure,然后在mutate!!进行评估

f1  <- function(dat, col1, col2) {
    col1 = enquo(col1)
    col2 = enquo(col2)
    dat %>%
        mutate(match = case_when(!! (col1) %in% !!(col2) ~ "has matches", 
                 TRUE ~ "no matches"))
}
f1(df, di, id)
#      id    di       match
#1   good     1  no matches
#2    bad     2  no matches
#3   ugly  good has matches
#4  dirty dirty has matches
#5  clean     4  no matches
#6 frenzy  ugly has matches