【问题标题】:Wrong output when counting words in multiple texts计算多个文本中的单词时输出错误
【发布时间】:2021-01-16 00:21:18
【问题描述】:

我有 2 个数据集,其中一个包含 500 个不同的实体,其中测量了一些变量。另一个有 500 个文本,每个文本属于第一个数据集中的实体。我想在这些文本中搜索 3 个关键字,并计算每个文本中出现的总关键字的次数。

一些作为随机表示的随机数据,keywords 是一个向量,texts 是一个包含文本的列表(我有一个列表,不知道我的示例列表是否正确),df 是数据框与我的实体的变量:

keywords <- c("ab", "cd", "ef")
texts <- as.list("ab is ef when ef is ef",
                 "something something nothing",
                 "cd is cd is ab is ab and ef")
var1 <- c("area1", "area2", "area3")
var2 <- c("15", "5", "23")
df <- data.frame(var1, var2)
colnames(df) <- c("location", "temperature")

这里的正确答案是关键字在第一个文本中出现 4 次,在第二个文本中出现 0 次,在第三个文本中出现 5 次。但是,当我尝试以下操作时,它会给出错误的输出:

df$count <- 0 # Store the results
# counting for all keywords
for(w in keywords){
  df$count <- 
    df$count + 
    grepl(w, texts, ignore.case = T)
 print(w)
}

df$count

关于我可以做什么的任何提示?最好有一些示例代码?

提前致谢

【问题讨论】:

    标签: r loops counting grepl


    【解决方案1】:

    您的texts 是一个列表。这有什么原因吗?而是让它成为一个向量。

    而且您还可以更轻松地数数。也许试试stringr 包。然后就可以了

    library(stringr)
    
    keywords <- c("ab", "cd", "ef")
    texts <- c("ab is ef when ef is ef",
                     "something something nothing",
                     "cd is cd is ab is ab and ef")
    
    str_count(texts, "ab|cd|ef")
    
    [1] 4 0 5
    

    如果你不能像上面那样设置模式,你也可以去

    str_count(texts, paste(keywords, collapse = "|"))
    

    【讨论】:

    • 谢谢,我应该更多地使用 stringr,但是我们的讲师只是向我们展示了很多循环和效率很低的东西。 Stringr 是文本分析的神模
    • 抱歉,听到这个。听起来您的讲师来自另一种编程语言。在 R 中,您通常会在 99% 的情况下避免循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    相关资源
    最近更新 更多