here is the answer using the R base (using apply
):
d <- data.frame(Origin = c("A01", "A02", "A03", "A01"), Destination = c("A01", "A01", "A01", "A02"), distance = c(0.0, 1.2, 1.4, 1.2), volume = c(10, 9, 15, 16))
d2 <- d[d[, "Destination"] == "A01", ]
greater_flow <- apply(d2, 1, FUN = function(x) max(sum(x['volume'] < d2[, 'volume']) - 1, 0) )
data.frame(d2, greater_flow)
if you need to perform a calculation for all possible destinations, you can simply go through unique(d[, "Destination"])
:
lapply(unique(d[, "Destination"]), FUN = function(dest){
d2 <- d[d[, "Destination"] == dest, ]
greater_flow <- apply(d2, 1, FUN = function(x) max(sum(x['volume'] < d2[, 'volume']) - 1, 0) )
data.frame(d2, greater_flow)
})
you can stick the output together, if necessary, through do.call(rbind, output)
.