r - 计算 R 中数据帧行中特定单词的出现次数

标签 r string count sum word-count

我有一个包含 2 列和多行的数据集。 第一列 ID,第二列属于它的文本。

我想添加更多的列来总结某个字符串在行的文本中出现的次数。字符串将是 "\n Positive\n", "\n Neutral\n", "\n Negativ\n"`

数据集示例:

Id, Content
2356, I like cheese.\n  Positive\nI don't want to be here.\n Negative\n
3456, I am alone.\n Neutral\n

最后应该是这样

Id, Content,Positiv, Neutral, Negativ
2356, I like cheese.\n  Positive\nI don't want to be here.\n Negative\n,1 ,0 ,1
3456, I am alone.\n Neutral\n, 0, 1, 0

现在我这样试过,但没有给出正确的答案:

getCount1 <- function(data, keyword)
{
Positive <- str_count(Dataset$CONTENT, keyword)
return(data.frame(data,Positive))
}
Stufe1 <-getCount1(Dataset,'\n Positive\n')
################################################################
getCount2 <- function(data,  keyword)
{
Neutral <- str_count(Stufe1$CONTENT, keyword)
return(data.frame(data,Neutral))
}
Stufe2 <-getCount2(Stufe1,'\n  Neutral\n')
#####################################################
getCount3 <- function(data,  keyword)
{
Negative <- str_count(Stufe2$CONTENT, keyword)
return(data.frame(data,Negative))
}
Stufe3 <-getCount3(Stufe2,'\n  Negative\n')

最佳答案

我假设这就是你需要的

示例数据

id <- c(1:4)
text <- c('I have a Dataset with 2 columns a',
          'nd multiple rows. first column ID', 'second column the text which',
          'n the text which belongs to it.')
dataset <- data.frame(id,text)

查找计数的函数

library(stringr)
getCount <- function(data,keyword)
{
  wcount <- str_count(dataset$text, keyword)
  return(data.frame(data,wcount))
}

调用 getCount 应该给出更新后的数据集

> getCount(dataset,'second')
  id                              text wcount
  1   I have a Dataset with 2 columns a      0
  2   nd multiple rows. first column ID      0
  3        second column the text which      1
  4     n the text which belongs to it.      0

关于r - 计算 R 中数据帧行中特定单词的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24550066/

相关文章:

c++ - 使用 C++ 的 Project Euler 17 字符串计数不正确

r - 与 S4 类相比,使用 setOldClass 时重载运算符无法按预期工作

c# - 为什么.net 对字符串使用 UTF16 编码,而保存文件却默认使用 UTF-8?

regex - 按空格拆分字符串,除非包含在引号中

PHP 添加单引号到逗号分隔列表

python - 如何在 python 中替换字符串的一部分?

mysql - 关联表中某个字段的计数和如何获取?

MySQL 连接来自另一个表的计数匹配记录,但我也需要零值

r - 绘图模型中的错误(类型="diag"): arguments imply differing number of rows error

r - 在 geom_smooth 阈值之外的 ggplot 中标记值