Maximilian Follet Maximilian Follet -4 years ago 104
R Question

Sum a value with two conditions in a Data Frame in R

I've a data frame with three date columns and one numeric column. The first one is when the customer open the purchase, the second the due date of the purchase, the third is the value of it and the last column is when the customer paid.

I would like to sum the value of purchases, by date, the amount of open purchases - which means not only not paid but less than the due time. The data frame is below:

set.seed(3)
open <- as.Date(rep(c("2017-03-22","2017-03-23","2017-03-24","2017-03-25"), 3), format = "%Y-%m-%d") #Purchase's open date
due <- open + 3 #Due date's purchase
purchase <- purchase <- round(runif(12, 50,150),2) #Quando ele gastou
paid <- as.Date(c("2017-03-22",NA,"2017-03-24","2017-03-25",NA,"2017-03-23",NA,"2017-03-25",NA,"2017-03-23",NA,NA)) #Value of purchase

base <- data.frame(open,due,purchase,paid)

Answer Source

Like this:

library(dplyr)
today <- Sys.Date()
base %>% group_by(open) %>% summarize(value_open = sum(purchase[today < due || is.na(paid)]))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download