代码之家  ›  专栏  ›  技术社区  ›  Alexander

搜索不同列中的匹配行

  •  0
  • Alexander  · 技术社区  · 7 年前

    我正在寻找一个函数,如果它找到匹配的行输出,那么它可以在列和输出之间找到匹配项 "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 回复  |  直到 7 年前
        1
  •  4
  •   Cath    7 年前

    使用 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
    
        2
  •  3
  •   akrun    7 年前

    仅使用 %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"))
    

    这可以直接包装在函数中。假设我们传递的是无引号的名称,然后将其转换为quosure enquo 然后在 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