r - 循环句子以查看句子是否包含触发词
问题描述
我有以下数据框。
sentences <- c("this is app is great", "the price it too high")
df <- data.frame(sentences)
我现在想遍历数据框中的每个句子,以查看句子是否包含列表中的单词。我设置了以下列表:
product_names <- c("app", "mega").
marketing_names <- c("campaign", "marketing").
price_names <- c("price", "expensive").
我写了以下代码:
for(i in 1:nrow(df)){
list = strsplit(df$sentences, " ")
for(l in list){
if(l %in"% product_names){
#Do something
print(l)
}
if(l %in"% marketing_names){
#Do something
}
if(l %in"% price_names){
#Do something
}
}
}
但这似乎不起作用,因为我没有受到打击。我应该在第一句话上受到打击。关于我做错了什么的任何反馈?
解决方案
很多小事。
数据框被解释为levels
and not character
,因此需要转换。
您尝试拆分df$sentences
,而不是df$sentences[i]
当前行。
最后,strsplit
返回一个列表,里面有一个数组,所以你需要先选择列表的第一个元素来访问单词数组。
将所有这些行放在一起变成:list = strsplit(as.character(df$sentences[i]), " ")[[1]]
最后,%in"%
应该读%in%
,所以最后的代码是:
sentences <- c("this is app is great", "the price it too high")
df <- data.frame(sentences)
product_names <- c("app", "mega")
marketing_names <- c("campaign", "marketing")
price_names <- c("price", "expensive")
for(i in 1:nrow(df))
{
list = strsplit(as.character(df$sentences[i]), " ")[[1]]
for(l in list)
{
if(l %in% product_names)
{
#Do something
print(paste(l,"found in product_names"))
}
if(l %in% marketing_names){
print(paste(l,"found in marketing_names"))
}
if(l %in% price_names){
print(paste(l,"found in price_names"))
}
}
}
推荐阅读
- angular - 如何访问全局变量的快照
- python - 对于组中的每个 ID,只保留组中的第一个值 !=0,将 other 设置为 0
- azure - 无法从连接到 Azure VPN 的本地计算机(在家庭网络上)访问专用 AKS 群集
- postgresql - 在 postgres 中转换一些表
- python - 在 Python 中向嵌套字典添加新键值的有效方法?
- python - GCP AI 平台统一:使用解析器/命令行参数时找不到存储桶
- ios - 状态栏上方的导航栏
- javascript - 我在遵循教程后得到的 Javascript 项目中出现“TypeError:无法读取未定义的属性‘长度’”错误。如何修复错误?
- r - 在 tidyverse 中使用 ifelse 更改多个值
- c - 执行整个代码之前的函数返回