str_extract() 和 summarise() 给我行

问题描述

这应该非常简单,因为我想我只是想验证我所看到的。

我正在尝试使用 str_extract() 从数据框中的列中提取感兴趣的区域,然后计算每个单词出现的频率。我遇到了一个问题,但是当我这样做时,我生成的数据框在其中一行中列出了 NA。这让我感到困惑,因为我不知道是什么导致了它,或者它是否是我的代码中出现错误的迹象。我不知道如何解决这个问题。

另外,请注意 words 中的最后一项是“the table is light”,其中包含本示例中感兴趣的两个单词。我故意这样做是因为我想确保它会被计算两次。

library(tidyverse)

df <- data.frame(words =c("paper book","food press","computer monitor","my fancy speakers","my two dogs","the old couch","the new couch","loud speakers","wasted paper","put the dishes away","set the table","put it on the table","lets go to church","turn out the lights","why are the lights on","the table is light"))

keep <- c("dogs|paper|table|light|couch")

new_df <- df %>% 
  mutate(Subject = str_extract(words,keep),n = n()) %>% 
  group_by(Subject)%>%
  summarise(`Word Count` = length(Subject))

这就是我现在得到的

 Subject `Word Count`
  <chr>          <int>
1 couch              2
2 dogs               1
3 light              2
4 paper              2
5 table              3
6 NA                 6

所以我的问题是 - 是什么导致了主题中的 NA 行?都是其他记录吗?

解决方法

对于 NA 中没有出现在该行中的单词的值,会出现 keep,因此没有任何可提取的内容。

library(dplyr)
library(stringr)

df %>%  mutate(Subject = str_extract(words,keep))

#                   words Subject
#1             paper book   paper
#2             food press    <NA>
#3       computer monitor    <NA>
#4      my fancy speakers    <NA>
#5            my two dogs    dogs
#6          the old couch   couch
#7          the new couch   couch
#8          loud speakers    <NA>
#9           wasted paper   paper
#10   put the dishes away    <NA>
#11         set the table   table
#12   put it on the table   table
#13     lets go to church    <NA>
#14   turn out the lights   light
#15 why are the lights on   light
#16    the table is light   table

例如,对于第 2 行 'food press',其中没有来自 "dogs|paper|table|light|couch" 的值,因此它返回 NA