【问题标题】:grepl across multiple columns - wildcard not working跨多个列的 grepl - 通配符不起作用
【发布时间】:2018-09-17 14:50:49
【问题描述】:

我目前正在处理具有多个相似列的数据集:item1、item2 等到 item8。在我正在编写的函数中,我创建了一个特定的搜索,用作 ifelse 函数中的第一个参数,该函数在以下任何列中搜索短语:

grepl(exact_name, item1) | grepl(exact_name, item2) | grepl(exact_name, item3) | grepl(exact_name, item4) | grepl(exact_name, item5) | grepl(exact_name, item6) | grepl(exact_name, item7) | grepl(exact_name, item8)

这很好用,但我希望能够将此函数应用于具有未知数量的项目列的数据框(所有使用的数据框将至少有一个项目列,如果它只有一个,它将仍然是 item1 的格式,而不仅仅是 item)。我尝试使用 * 通配符如下:

grepl(exact_name, item*)

但我在 item* 后面加上括号时出现错误,甚至无法运行该部分。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: r wildcard grepl


    【解决方案1】:

    如果item\\d+是全局环境中的对象,我们可以使用mget获取list中的对象,然后循环遍历list,将greplReduce应用于单个逻辑vector

    Reduce(`|`,lapply(mget(ls(pattern = "^item\\d+$")), grepl, pattern = exact_name))
    

    如果item\\d+ 是数据集中的列,请使用filter_at

    library(dplyr)
    df1 %>%
       filter_at(vars(matches("^item\\d+$")), any_vars(str_detect(., exact_name)))
    

    另外,如果我们不进行部分匹配,那么 == 也应该可以工作

    df1 %>%
       filter_at(vars(matches("^item\\d+$")), any_vars(.== exact_name))
    

    【讨论】:

    • 这给了我这个错误:Error in mutate_impl(.data, dots) : Evaluation error: object of type 'builtin' is not subsettable.我该如何解决这个问题?
    • @ClaraR。从帖子中不清楚item1item2 等的结构。这些是向量还是 data.frames ?请显示“item1”的较小子集的dput
    • @ClaraR。我更新了帖子请检查是否有效
    • 它们是数据框中的向量。 dput(test_frame$item1[1:3] 返回c("Benjamin Wells Robinson", "Benjamin Wells Robinson", "Martha Ann Walls Robinson")
    • @ClaraR。在这种情况下,请尝试使用第二组代码。一个可重现的示例对于测试的预期输出会很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    相关资源
    最近更新 更多