【问题标题】:Can you use grepl with row values?您可以将 grepl 与行值一起使用吗?
【发布时间】:2020-11-23 20:17:33
【问题描述】:

我正在尝试查看用户名数据框是否包含来自另一个数据框的全名。

我正在遍历每个用户名并使用 grepl 来查看用户名是否包含来自不同数据帧的名字和姓氏。

我试过了:

    matches <- 0
    for (i in df1$usernames)
    {
      if (grepl(df2$FIRST_NAME, i, fixed=TRUE) & grepl(df2$LAST_NAME, i, fixed=TRUE))
      {
         matches <- matches+1
      }
     }

是否可以将 grepl 用于列中的值,而不是字符串?因为它不起作用 - 如果没有,我还能如何查看一行的名字和姓氏是否在用户名中。

例如John123Doe, JohnDoe123, JohnDoe 应该都与包含 "John""Doe" 的行匹配

【问题讨论】:

    标签: r regex grepl


    【解决方案1】:

    你可以这样做:

    df1 <- data.frame(username=c("John123Doe", "JohnDoe123", "JohnDoe", "JonDoe", "YonDo"))
    df2 <- data.frame(First=c("Jack","Joe", "Jon", "John", "Jo"), 
                      Last=c("Doe", "Dohe", "Doer", "Doe", "Do"))
    
    findUser <- function(x) {
      res <- apply(df2, 1, function(y) grepl(y["First"], x) & grepl(y["Last"], x))
      ifelse(sum(res) > 0, paste(do.call("paste", df2[res,]), collapse=", "), NA)
    }
    
    df1$containsUserName <- sapply(df1$username, findUser)
    
    df1
    #>     username containsUserName
    #> 1 John123Doe  John Doe, Jo Do
    #> 2 JohnDoe123  John Doe, Jo Do
    #> 3    JohnDoe  John Doe, Jo Do
    #> 4     JonDoe            Jo Do
    #> 5      YonDo             <NA>
    
    # or vectorize the function:
    FindUser <- Vectorize(findUser)
    FindUser(df1$username)
    #>        John123Doe        JohnDoe123           JohnDoe            JonDoe 
    #> "John Doe, Jo Do" "John Doe, Jo Do" "John Doe, Jo Do"           "Jo Do" 
    #>             YonDo 
    #>                NA
    

    reprex package (v0.3.0) 于 2020 年 8 月 3 日创建

    【讨论】:

    • 当我这样做时,我得到:$&lt;-.data.frame(*tmp*, containsUserName, value = list()) 中的错误:替换有 0 行,数据有 22873
    • 是使用上面的示例(应该是可重现的),还是您自己的数据结构?听起来您的 df1 没有名为 username 的列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多