【问题标题】:Multiple partial string matches in dataframe count数据帧计数中的多个部分字符串匹配
【发布时间】:2018-05-13 15:48:08
【问题描述】:

我一直在寻找其他主题的解决方案,但没有找到。我正在寻找几个部分字符串匹配。字符串在数据框中,但我也在(字符)向量中尝试过。

示例输入:

authors <- c("Edward","Kelly","Simon")
df <- 
Text                                 Date      
Edward was the king of ...           2011          
Kelly has ..                         2014           
Last year Simon..                    2009           
Did you know Edward..                1999     

我想要的输出是:

Author                               Count 
Edward                                2
Kelly                                 1           
Simon                                 1

同样重要的是,列文本中的每一行只匹配一次。因此,如果名称在输入单元格中被提及两次,它仍然应该只匹配一次。

我尝试过类似的方法:

sum(str_count(df$Text,c("Edward")))

这适用于一个输入名称,但不适用于多个。我希望有人可以帮助我解决这个问题

【问题讨论】:

    标签: r string count pattern-matching


    【解决方案1】:

    我们可以遍历 'authors',获取 str_countsumenframe 它以获取单个数据集

    library(tidyverse)
    map_df(authors, ~ str_count(df$Text, .x) %>% 
                           sum %>%
                           set_names(.x) %>% 
                           enframe(name = "Author", value = "count")) %>%
        arrange(desc(count))
    # A tibble: 3 x 2
    #  Author    count
    #   <chr>  <int>
    #1 Edward     2
    #2 Kelly      1
    #3 Simon      1
    

    【讨论】:

    • 非常感谢,这正是我需要的!有没有办法将 desc = T 参数传递给 tibble?
    • @Bastje 更新了帖子
    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 2020-11-28
    • 2019-09-02
    • 2020-08-31
    • 2015-02-12
    • 2021-08-11
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多