r - 根据 quanteda 字典查找生成 dummy
问题描述
我正在使用 quanteda 创建字典并查找术语。
这是我的数据的可重现示例:
dput(tweets[1:4, ])
structure(list(tweet_id = c("174457180812_10156824364270813",
"174457180812_10156824136360813", "174457180812_10156823535820813",
"174457180812_10156823868565813"), tweet_message = c("Climate change is a big issue",
"We should care about the environment", "Let's rethink environmental policies",
"#Davos WEF"
), date = c("2019-03-25T23:03:56+0000", "2019-03-25T21:10:36+0000",
"2019-03-25T21:00:03+0000", "2019-03-25T20:00:03+0000"), group = c("1",
"2", "3", "4")), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"))
以下是我根据从该论坛获得的建议使用字典的方式:
climate_corpus <- corpus(tweets, text_field = "tweet_message")
climatechange_dict <-
dictionary(list(climate = c("environment*", "climate change")))
groupeddfm <- tokens(climate_corpus) %>%
tokens_lookup(dictionary = climatechange_dict) %>%
dfm(groups = "group")
convert(groupeddfm, to = "data.frame")
我需要做的是在我的原始数据集“tweets”中创建一个等于 1 的虚拟对象,当 tokens_lookup 在一个特定的观察(推文)中识别出我的字典中包含的一个单词时。使用我的可重现示例,我想为前三个观察(它们包括字典单词)生成一个等于 1 的虚拟对象,而为第四个观察(没有字典单词)生成一个等于 0 的虚拟对象。
我非常感谢您在这方面的帮助。非常感谢!
解决方案
library("quanteda")
## Package version: 2.0.1
tweets <- structure(
list(tweet_id = c(
"174457180812_10156824364270813",
"174457180812_10156824136360813", "174457180812_10156823535820813",
"174457180812_10156823868565813"
), tweet_message = c(
"Climate change is a big issue",
"We should care about the environment", "Let's rethink environmental policies",
"#Davos WEF"
), date = c(
"2019-03-25T23:03:56+0000", "2019-03-25T21:10:36+0000",
"2019-03-25T21:00:03+0000", "2019-03-25T20:00:03+0000"
), group = c(
"1",
"2", "3", "4"
)),
row.names = c(NA, -4L), class = c(
"tbl_df",
"tbl", "data.frame"
)
)
climate_corpus <- corpus(tweets, text_field = "tweet_message")
climatechange_dict <-
dictionary(list(climate = c("environment*", "climate change")))
groupeddfm <- tokens(climate_corpus) %>%
tokens_lookup(dictionary = climatechange_dict) %>%
dfm(groups = "group")
tweets$mentions_climate <- as.logical(groupeddfm[, "climate"])
tweets
## # A tibble: 4 x 5
## tweet_id tweet_message date group mentions_climate
## <chr> <chr> <chr> <chr> <lgl>
## 1 174457180812_1015… Climate change is a b… 2019-03-25T2… 1 TRUE
## 2 174457180812_1015… We should care about … 2019-03-25T2… 2 TRUE
## 3 174457180812_1015… Let's rethink environ… 2019-03-25T2… 3 TRUE
## 4 174457180812_1015… #Davos WEF 2019-03-25T2… 4 FALSE
推荐阅读
- networking - 如何指示移动节点沿特定轨迹移动?
- linux - 使用 tar 备份非常大的压缩文件时使用临时文件和内存
- sql - 使用字母表达式创建插入
- google-apps-script - 检索 Google 用户并将其用作 Google Data Studio 中的数据
- java - JButton 不需要的文本大小更改
- javascript - 如何在链接点击时获取输入字段值?
- javascript - 清除自动 Setinterval 以打开模式
- c - C中的递归合并排序不修改原始数组
- typescript - 带有回调函数的打字稿计时器我可以等待
- string - 我们如何在 Elastic Search 中插入文档?‽‽?