r - R:使用一组数据框/单词字典交叉检查文本文档
问题描述
刚接触 R 和编码,我还是个学生。我有一个文本文档,想对我已经清理的字典/df 集进行交叉检查,并将文档标记为它的根词。目标是交叉检查 Document1 与 dictionary1 以查看 document1 中是否有任何单词与字典中的单词匹配。如果是,则文档将根据其类别进行标记。该示例将如下所示:
Document1 <- "One simple text"
dictionary1 <- data.frame("Term"= c("teacher", "simple", "shoot", "text"))
if (strcmp(Document1, dictionary1)){
print('Success')
} else {
print('Failed')
}
我尝试使用此代码的结果将打印为“失败”,即使 Document1 中有匹配的单词“simple”和“text”。我该如何解决这个问题?我是否需要先在 document1 上进行strsplit,然后使用strcmp函数进行比较?提前感谢任何可以为此提供解决方案的人。为我糟糕的英语道歉。
解决方案
欢迎来到 SO,我们可以在 r 中的 data.frame 中编写大部分内容
library(tidyverse)
Document1 <- "One simple text"
dictionary1 <- data.frame("Term" = c("teacher", "simple", "shoot", "text"))
df_results <- dictionary1 %>%
mutate(result = str_detect(string = Document1, pattern = Term))
df_results
#> Term result
#> 1 teacher FALSE
#> 2 simple TRUE
#> 3 shoot FALSE
#> 4 text TRUE
if (any(df_results$result == TRUE)) {
print("Sucess")
} else {
print("Failure")
}
#> [1] "Sucess"
Document1 <- "Nothing Matters"
dictionary1 <- data.frame("Term" = c("teacher", "simple", "shoot", "text"))
df_results <- dictionary1 %>%
mutate(result = str_detect(string = Document1, pattern = Term))
df_results
#> Term result
#> 1 teacher FALSE
#> 2 simple FALSE
#> 3 shoot FALSE
#> 4 text FALSE
if (any(df_results$result == TRUE)) {
print("Sucess")
} else {
print("Failure")
}
#> [1] "Failure"
# Another way is using vectors
Document1 <- "simple right"
dictionary1 <- data.frame("Term" = c("teacher", "simple", "shoot", "text"))
result <- str_detect(string = Document1, pattern = dictionary1$Term)
result
#> [1] FALSE TRUE FALSE FALSE
if (any(result == TRUE)) {
print("Sucess")
} else {
print("Failure")
}
#> [1] "Sucess"
由reprex 包于 2020-06-11 创建(v0.3.0)
推荐阅读
- radio-button - boostrap5 单选按钮名称组
- c# - 模板还是用户控件?哪个?
- r - 根据每组的值填充百分比堆积条形图,R
- markdown - Github Pages - 用于更好地呈现代码片段的降价
- c# - 构建后从 android 9-Pie 为 android 10-Q 升级 sdk 29 时出错,我在调试和发布时都得到可调试的未设置错误。(Xamarin 形式)
- awk - 将第一个文件的第一列与第二个文件中的行匹配,然后将第二个文件中匹配行的最后一列插入第一个文件中的新第一列
- flutter - 参数类型 'Future
Function()' 不能分配给参数类型'Future ' - r - 如何从方括号列表中提取元素?
- c# - 如何在 Xamarin / C# 中使用 FirebaseCrashlytics.Instance.RecordException?
- node.js - 通过电子邮件链接打开本地环境页面