我有一个每日收入的数据框:
date earning
1 -40.495074
2 -88.636625
3 134.400976
4 66.325253
5 -86.337511
6 -1.266815
7 267.944212
8 65.247053
9 86.177537
10 64.540579
我希望每7天分组一次,并使用中位数累计7天。
edit1:它不一定是日历周,只是任意7天组。
所以就像
week median-earning
1 11
2 22
依旧......
我如何在R?
中实现这一目标答案 0 :(得分:4)
library(dplyr)
theData <- data.frame(date = 1:10,
earning = c(-40, -88, -134, 66, -86, -1, 267, 65, 86, 64))
theData$seven_day_index <- c(0, rep(1:(nrow(theData)-1)%/%7))
group_by(theData, seven_day_index) %>%
summarise(median_earnings = median(earning))
和基础R版本
sapply(split(theData$earning, c(0, rep(1:(nrow(theData)-1)%/%7))), median)
编辑:受上述启发
theData %>% mutate(seven_day_index = 1:nrow(theData) %/% 7) %>%
group_by(seven_day_index) %>%
summarise(median_earnings = median(earning)