在較大型資料集上使用「or 樣式」
既然你已經理解如何從向量串接多種可能性,接下來就更進一步,把這個做法用在較大的資料集上。全域範圍中有兩個變數可用:articles 與 politicians。前者是關於瑞士政治的新聞文章集合;後者是出現在這些文章中的瑞士政治人物姓名清單。
現在就交給你來找出:哪些姓名出現在哪些文章裡,以及每位政治人物在所有文章中分別出現了幾次。
本練習屬於課程
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, ___)