开始使用免费开始使用

在更大的数据集上使用"或模式"

现在,您已经理解了从向量拼接多种可能性的原理。接下来请把它应用到更大的数据集上。全局作用域中提供了两个变量:articlespoliticians。前者是关于瑞士政治的新闻文章集合,后者是在文章中出现的瑞士政治人物姓名列表。

现在,请您找出哪些姓名出现在了哪些文章中,以及每位政治人物在所有文章中一共出现了多少次。

本练习是课程的一部分

R 中级正则表达式

查看课程

练习说明

  • 使用向量 politicians 创建一个能匹配该向量中所有姓名的正则表达式。
  • 在数据框 articles 中创建一个新列,包含出现在 text 列中的所有政治人物姓名。
  • 将所有文章粘合在一起,便于按政治人物统计出现次数。
  • 将向量 politicians 作为模式传给 str_count()

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Construct a pattern that searches for all politicians
polit_pattern <- glue_collapse(___, sep = "___")

# Use the pattern to match all names in the column "text"
articles %<>%
  mutate(mentions = str_match_all(___, ___))

# Collapse all items of the column "text"
all_articles_in_one <- ___(articles$text)

# Pass the vector politicians to count all its elements
str_count(all_articles_in_one, ___)
编辑并运行代码