将df作为:
ID Status Created_Date Booking_Date Price_Booking
1 Confirmed "2013-03-01" "2013-08-21" 400
1 Confirmed "2013-03-01" "2013-10-01" 350
2 Confirmed "2013-04-11" "2013-10-01" 299
2 Confirmed "2013-04-11" "2013-10-01" 178
3 Cancelled "2013-02-21" "2014-04-01" 99
4 Confirmed "2013-08-30" "2013-10-01" 525
5 Confirmed "2014-01-01" "2014-12-01" 439
6 Confirmed "2015-02-22" "2015-11-18" 200
6 Confirmed "2015-07-13" "2017-04-09" 100
想根据Created_Date变量计算第一年每位客户的收入。
我尝试过:
with(df$ID[df$Status=="Confirmed" & format(as.Date(df$Created_Date), "%Y") == 2013 & format(as.Date(df$Booking_Date), "%Y") == 2013]))
但是,这仅计算每个日历年的收入,我希望相对于Created_Date
预期输出为:
ID Sum_Price_Booking
1 750
2 477
3 NA
4 525
5 439
6 200
答案 0 :(得分:1)
对于group_by
和ID
之间的差异小于1年的那些值,我们可以sum
Price_Booking
和Booking_Date
Created_Date
个值
library(dplyr)
df %>%
mutate_at(vars(ends_with("Date")), as.Date) %>%
group_by(ID) %>%
summarise(sum = sum(Price_Booking[Booking_Date - Created_Date < 365]))
# ID sum
# <int> <int>
#1 1 750
#2 2 477
#3 3 0
#4 4 525
#5 5 439
#6 6 200
数据
df <- structure(list(ID = c(1L, 1L, 2L, 2L, 3L, 4L, 5L, 6L, 6L),
Status = structure(c(2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L),
.Label = c("Cancelled", "Confirmed"), class = "factor"),
Created_Date = structure(c(2L, 2L, 3L, 3L, 1L, 4L, 5L, 6L, 7L),
.Label = c("2013-02-21", "2013-03-01", "2013-04-11", "2013-08-30", "2014-01-01",
"2015-02-22", "2015-07-13"), class = "factor"), Booking_Date =
structure(c(1L, 2L, 2L, 2L, 3L, 2L, 4L, 5L, 6L),
.Label = c("2013-08-21", "2013-10-01", "2014-04-01", "2014-12-01", "2015-11-18",
"2017-04-09"), class = "factor"), Price_Booking = c(400L, 350L, 299L, 178L, 99L,
525L, 439L,200L, 100L)), class = "data.frame", row.names = c(NA, -9L))
答案 1 :(得分:0)
您可以使用data.table方式通过=选择聚合
UIView