開始使用免費開始

在較大型資料集上使用「or 樣式」

既然你已經理解如何從向量串接多種可能性,接下來就更進一步,把這個做法用在較大的資料集上。全域範圍中有兩個變數可用:articlespoliticians。前者是關於瑞士政治的新聞文章集合;後者是出現在這些文章中的瑞士政治人物姓名清單。

現在就交給你來找出:哪些姓名出現在哪些文章裡,以及每位政治人物在所有文章中分別出現了幾次。

本練習屬於課程

R 中級 Regular Expressions

檢視課程

練習說明

  • 使用向量 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, ___)
編輯並執行程式碼