我有一个包含 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/