【问题标题】:Filter a column based on a word and perform calculation on another two columns根据一个词过滤一列,对另外两列进行计算
【发布时间】:2019-08-02 12:59:25
【问题描述】:

如果这看起来像一个重复的问题,请原谅。我进行了长时间的搜索,但无法归零。

我有一个数据集,其中有一列是文本,另一列是文本的第一个单词。

还有两列用于显示文本发送的人数和阅读人数。

样本数据:

df <- data.frame(Word = c("Happy", "Good", "Have", "Do"), 
                 Text = c("Happy Birthday", "Good Morning", "Have a good day", 
                           "Do you have happy news"), 
                  Sent = c(10, 20, 15, 20), 
                  Read = c(8, 12, 9, 13), stringsAsFactors = FALSE)

我想计算每个单词的阅读率。它是从包含该单词的文本中计算出来的

我尝试了以下代码,但似乎永远运行,但没有任何错误消息。

我知道在我的情况下 for 循环对于 18K 记录效率不高,并且在 R 中更喜欢一种有效的解决方案。

感谢您在这方面的任何帮助。

for (i in 1:nrow(messages)){

  word <- messages$Word[i]
  messages$Rate[i] <- messages%>% filter(str_detect(string = Text, pattern = word)) %>% summarise(sum(Read)/sum(Sent))

}

【问题讨论】:

  • 请编辑您的问题并通过粘贴dput(messages) 的输出或您的数据子集来提供可重现的示例。
  • 添加了创建示例数据的代码。复制自 Ronak 下面的回答。感谢他。

标签: r string loops dplyr


【解决方案1】:

使用基本 R sapply 的一种方法,对于每个 Word,我们找出 Word 在数据帧中出现的索引 (inds)。我们使用这些索引对和sumReadSent 列进行子集化并计算比率。

df$Rate <- with(df, sapply(Word, function(x) {
          inds = grep(paste0("\\b", x, "\\b"), Text, ignore.case = TRUE)
          sum(Read[inds])/sum(Sent[inds])
}))


df
#   Word                   Text Sent Read      Rate
#1 Happy         Happy Birthday   10    8 0.7000000
#2  Good           Good Morning   20   12 0.6000000
#3  Have        Have a good day   15    9 0.6285714
#4    Do Do you have happy news   20   13 0.6500000

如果您更喜欢tidyverse 的方法,请使用map_dbl 做同样的事情

library(tidyverse)
df %>%
   mutate(Ratio = map_dbl(Word, function(x) {
                   inds = str_detect(Text, fixed(x, ignore_case=TRUE))
                    sum(Read[inds])/sum(Sent[inds])
}))

数据

df <- data.frame(Word = c("Happy", "Good", "Have", "Do"), 
                 Text = c("Happy Birthday", "Good Morning", "Have a good day", 
                           "Do you have happy news"), 
                  Sent = c(10, 20, 15, 20), 
                  Read = c(8, 12, 9, 13), stringsAsFactors = FALSE)

【讨论】:

  • .. 你是明星,感激不尽。它就像一个魅力。我一直在努力解决这个问题几个小时。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多