R:根据条件从两个数据帧聚合

标签 r dataframe conditional-statements aggregate multiple-columns

我有一个名为“e”的数据框,其中包含来自平台的帖子,具有唯一的entry_id和member_id:

row.    member_id   entry_id        timestamp
1       1            a              2008-06-09 12:41:00
2       1            b              2008-07-14 18:41:00
3       1            c              2010-07-17 15:40:00
4       2            d              2008-06-09 12:41:00
5       2            e              2008-09-18 10:22:00
6       3            f              2008-10-03 13:36:00

我有另一个名为“c”的数据框,其中包含注释:

row.    member_id   comment_id      timestamp
1       1            I              2007-06-09 12:41:00
2       1            II             2007-07-14 18:41:00
3       1            III            2009-07-17 15:40:00
4       2            IV             2007-06-09 12:41:00
5       2            V              2009-09-18 10:22:00
6       3            VI             2010-10-03 13:36:00

我想统计成员(member)在发布条目之前所写的所有评论。所以数据框“e”应该看起来像这样。阅读示例时只需注意年份。然而,解决方案也应该持续几分钟:

row.    member_id   entry_id    prev_comment_count  timestamp
1       1            a              2              2008-06-09 12:41:00
2       1            b              2              2008-07-14 18:41:00
3       1            c              3              2010-07-17 15:40:00
4       2            d              1              2008-06-09 12:41:00
5       2            e              1              2008-09-18 10:22:00
6       3            f              0              2008-10-03 13:36:00

我已经尝试过以下功能:

functionPrevComments <- function(givE)  nrow(subset
(c, (as.character(givE["member_id"]) == c["member_id"]) & 
(c["timestamp"] <= givE["timestamp"])))

但是当我尝试应用它时,出现错误

"Incompatible methods ("Ops.data.frame", "Ops.factor") for "<=""

我使用“$”运算符来引用我之前需要的列,但后来我得到了

"$ operator is invalid for atomic vectors "

如何正确应用我的功能,或者是否有其他更好的解决方案来解决我的问题?

最诚挚的问候,

尼古拉斯

最佳答案

这里有一个稍微不同的选项。在运行代码之前,请确保将两个“时间戳”列都转换为 POSIXct 类。

e$prev_comment_count <- sapply(seq_len(nrow(e)), function(i) {
  nrow(c[c$member_id == e$member_id[i] & c$timestamp < e$timestamp[i], ])
})

e
#  row. member_id entry_id           timestamp prev_comment_count
#1    1         1        a 2008-06-09 12:41:00                  2
#2    2         1        b 2008-07-14 18:41:00                  2
#3    3         1        c 2010-07-17 15:40:00                  3
#4    4         2        d 2008-06-09 12:41:00                  1
#5    5         2        e 2008-09-18 10:22:00                  1
#6    6         3        f 2008-10-03 13:36:00                  0

关于R:根据条件从两个数据帧聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28010772/

相关文章:

r - 如何在每个条形顶部显示百分比标签

matlab - 基于matlab中条件的每个单元格操作

java - java中num%2是什么意思?

狂欢 "not": inverting the exit status of a command

r - Emacs ESS 模式 - 注释区域的 Tab 键切换

r - xtable和knitr : How to center table on full page width?

R 高效过滤数据帧(由用户定义的不同过滤器)

python - 如何找到数据框中列的最小值的第一行

Python/Pandas传输dataframe的格式

pandas - 当我将 Pandas 系列插入数据框时,所有值都变为 NaN