我正在尝试使用此数据集中的日期对ID进行分组,但我想基于该组之外的某个功能进行汇总 .
library(dplyr)
library(lubridate)
set.seed(100)
df <- data.frame(ids = sample(c('436247', '2465347', '346654645'), 10000, replace=TRUE),
date = sample(seq.Date(ymd('2018-03-01'), ymd('2018-05-01'), by=1), 10000, replace=TRUE))
new_df <- df %>%
group_by(ids, date) %>%
summarise(events = length(ids[date >= date - 30 & date <= date]))
我正在尝试使用此数据框并回答问题 - "for each of the ids, and each date, how many other records within that id, are within the past 30 days of that date" . 不幸的是,当我 group_by
ids和日期时,它只在分组日期内查看 . 我在下面创建了解决方案,但不确定dplyr是否有更好的解决方案?
groupby_function <- function(df, spec_date){
result <- df %>%
group_by(ids) %>%
summarise(events = length(ids[date >= spec_date - 30 & date <= spec_date])) %>%
mutate(date = spec_date)
return(result)
}
date_vector <- seq.Date(ymd('2018-03-01'), ymd('2018-05-01'), by=1)
list_results <- lapply(date_vector, groupby_function, df=df)
x <- do.call(rbind, list_results)
4 回答
为此,"join by"条件是有道理的,但isn't yet included in dplyr . 在此之前,您可以在dplyr链中使用data.table:
我认为它应该适用于平等条件写
ids = id
或ids == id
.如果您有兴趣,语法是
x[i, on=, j, by=.EACHI]
,其中x
和i
是表格 . 对于i
的每一行,我们根据on=
条件查找x
的行(左侧是指x
中的列;右侧是i
中的列);那么我们每个都做j
(“每行i
”所以by=.EACHI
) . 在这种情况下,j = .N
表示我们计算匹配的x
行,作为计数列N
返回 .您只需返回原始数据框(调用
df$date
或df$ids
)即可查看"ungrouped"数据 . 所以我认为你所追求的是另外,我运行了你提出的函数,但我没有看到原始
group_by
解决方案的结果有任何差异,所以我认为这不是你想要的 .如果“非dplyr”解决方案是可以接受的,那么这可以为您提供所需的解决方案 .
或者,在
dplyr
中,您可以使用以下方式获得如上所示的结果:这里's an answer. But it assumes there'是每个
id
的连续日期序列 .