[英]Using the results from a Quanteda KWIC to count a number of "NOT" occurances (R)
我正在嘗試捕獲大量評論中“不”字詞后關鍵字出現的次數,以衡量情緒。 為了捕獲非詞后面的詞,我使用了 Quanteda 的 KWIC,並根據 KWIC 中的 window 后綴為關鍵字創建了一個 dtm。 我的問題是 KWIC dataframe 比原來的 dataframe 小,因此找不到相應的事件。
我有這個:
library(dplyr)
library(quanteda)
text_column <- c("not safe","not safe and not listening","not safe never patient", "safe","not welcoming","nice people","corporate culture school tacos","successful words words coding")
test.df <- as.data.frame(text_column)
notwords <- c("not", "never", "don't", "seldom", "won't")
dictionary(list(possafety = c("open","open-minded", "listen*", "safe*", "patien*", "underst*", "willing to help", "helpful", "tight-knit", "hear*", "engage*", "support*", "comfortable", "belong*", "welcom*", "inclu*", "value", "respect*", "always someone you can go to for questions", "accept*")
行號 | 文本 |
---|---|
1個 | 不安全 |
2個 | 不安全,不聽 |
3個 | 不安全,從不耐心 |
4個 | 安全的 |
5個 | 不歡迎 |
6個 | 好人 |
7 | 企業文化學校炸玉米餅 |
8個 | 成功的詞詞編碼 |
我想得到這個:
行號 | 文本 | 不安全 |
---|---|---|
1個 | 不安全 | 1個 |
2個 | 不安全,不聽 | 2個 |
3個 | 不安全,從不耐心 | 2個 |
4個 | 安全的 | 0 |
5個 | 不歡迎 | 1個 |
6個 | 好人 | 0 |
7 | 企業文化學校炸玉米餅 | 0 |
8個 | 成功的詞詞編碼 | 0 |
我嘗試創建一個行號變量,過濾 KWIC dataframe 的出現,並使用 ifelse 語句驗證是否在 dataframe 中找到行號,但這仍然只給我一個 0 或一個 1,我需要計算實例就像在第 2 行和第 3 行中出現不止 1 次。
not.df <- as.data.frame(kwic(test.df$text, pattern = not, window = 2))
not.df$rownumber <- as.numeric(gsub(".*?([0-9]+).*", "\\1", not.df$docname))
corptextnot <- corpus(not.df, text_field = "post")
dtmtextnot <- dfm(corptextnot)
dict_dtmtextnot = dfm_lookup(dtmtextnot, dict, exclusive = TRUE)
nottextdict.df <- as.data.frame(dict_dtmtextnot)
not.df$safe <- nottextdict.df$possafety
not.df <- filter(not.df, safe > 0)
test.df$notpossafe <- ifelse((test.df$rownumber %in% not.df$rownumber), 1,0)
這只會給我:
行號 | 文本 | 不安全 |
---|---|---|
1個 | 不安全 | 1個 |
2個 | 不安全,不聽 | 1個 |
3個 | 不安全,從不耐心 | 1個 |
4個 | 安全的 | 0 |
5個 | 不歡迎 | 1個 |
6個 | 好人 | 0 |
7 | 企業文化學校炸玉米餅 | 0 |
8個 | 成功的詞詞編碼 | 0 |
有沒有一種方法可以計算 elseif 測試為正的次數或出現次數並使該數字成為數字,或者有沒有一種方法可以在兩個不同大小的數據幀之間找到相應的值,或者更根本的是,是否有更好的工具可以做我想做什么?
您可以使用stringr
stringr::str_count
和 stringr package 並使用collapse = "|"
paste
:
test.df$notpossafe <- stringr::str_count(test.df$text_column,
paste(notwords, collapse = "|"))
Output:
# text_column notpossafe
# 1 not safe 1
# 2 not safe and not listening 2
# 3 not safe never patient 2
# 4 safe 0
# 5 not welcoming 1
# 6 nice people 0
# 7 corporate culture school tacos 0
# 8 successful words words coding 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.