【问题标题】:Speed up string filtering in R加快 R 中的字符串过滤
【发布时间】:2018-04-05 18:22:21
【问题描述】:

我有一个数据框,其中有一列以逗号分隔的代码。我目前正在通过查看代码列来过滤此数据框,如果列表中出现代码,我会保留该行。我的问题是这个数据框正在扩展,可接受的代码列表也是如此,所以如果可能的话,我想加快这个过程。理想情况下,有一种方法可以将一行标记为已检查,如果该行中有一个好的代码,则不必再次检查所有其他可接受的代码。

当前数据框如下所示:

Code_column
,12ab,
,12ab,123b,
,456t,345u,
,12ab,789p,

好代码列表:

good_codes <- c(',123b,', ',456t,', ',345u,')

我目前的过滤过程:

df %>%
filter(sapply(`Code_column`, 
            function(x) any(sapply(good_codes, str_detect, string = x))) == TRUE)

最后一栏

Code_column
,12ab,123b,
,456t,345u,

【问题讨论】:

    标签: r string dplyr sapply stringr


    【解决方案1】:

    我认为我们不需要sapply

    df[str_detect(df$Code_column,paste(good_codes, collapse = '|')),]
    [1] ",12ab,123b," ",456t,345u,"
    

    你可以通过 |与str_detect

    paste(good_codes, collapse = '|')
    [1] ",123b,|,456t,|,345u,"
    

    【讨论】:

    • 我认为这也是基础 R 中的df[ grepl(paste(good_codes, collapse='|'), df$CCode_column),]
    猜你喜欢
    • 2019-11-02
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2019-10-23
    相关资源
    最近更新 更多