R - If date falls within range, then sum

耗尽温柔 提交于 2019-12-05 15:12:11

First we need to make sure your date formats etc are correct. I'll assume they are, my versions are at the end. You have't provided a dput and have some weird column names, so double check spacing and capitals.

Next, let's construct an interval object for each campaign from the library lubridate:

library(lubridate)
MediaPlanDF$interval <- interval(MediaPlanDF$Campaign.flight.1, MediaPlanDF$end.date)

Now we can test if each item in outputDF is in each interval, and if so, sum it (your test data has all elements in all intervals):

output <- do.call(rbind, lapply(OutputDF$Date, function(x){
                              index <- x %within% MediaPlanDF$interval;
                              list(impressions = sum(MediaPlanDF$dailyimpressions[index]),
                                   spend = sum(MediaPlanDF$dailyspend[index]))}))

Where we get the output:

cbind(output, OutputDF)
  impressions    spend       Date
1    684285.7 3657.143 2015-08-31
2    684285.7 3657.143 2015-09-01
3    684285.7 3657.143 2015-09-02
4    684285.7 3657.143 2015-09-03
5    684285.7 3657.143 2015-09-04
6    684285.7 3657.143 2015-09-05

data:

OutputDF:

structure(list(Date = structure(c(16678, 16679, 16680, 16681, 
16682, 16683), class = "Date")), .Names = "Date", row.names = c(NA, 
-6L), class = "data.frame")

MediaPlanDF:

structure(list(daysinflight = c(35L, 35L, 35L, 35L), dailyimpressions = c(392857.1429, 
85714.28571, 142857.1429, 62857.14286), dailyspend = c(1571.428571, 
428.5714286, 714.2857143, 942.8571429), Campaign.name = structure(c(1L, 
1L, 1L, 1L), .Label = "A", class = "factor"), Campaign.ID = structure(c(1L, 
1L, 1L, 1L), .Label = "Real", class = "factor"), Campaign.flight = structure(c(1L, 
1L, 1L, 1L), .Label = "Advertiser", class = "factor"), start.date = structure(c(1L, 
1L, 1L, 1L), .Label = "RAND0M", class = "factor"), Campaign.flight.1 = structure(c(16678, 
16678, 16678, 16678), class = "Date"), end.date = structure(c(16712, 
16712, 16712, 16712), class = "Date")), .Names = c("daysinflight", 
"dailyimpressions", "dailyspend", "Campaign.name", "Campaign.ID", 
"Campaign.flight", "start.date", "Campaign.flight.1", "end.date"
), row.names = c(NA, -4L), class = "data.frame")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!