lib(reshape2) colsUsing <- c("month", "country_code", "product_type", "rightholders_tracks", "total_tracks", "registered_users", "active_users") byCols <- setdiff(colsUsing, c("rightholders_tracks", "total_tracks")) stopifnot(DT.revsharecrop[, .N, by=byCols][, N==1]) DT.rev2 <- DT.revsharecrop[, list(O_v_S=c("Orchard", "Spotify"), Streams=c(rightholders_tracks, total_tracks)), keyby=byCols] DT.rev2[, streams_diff := if (length(Streams) == 0) numeric() else if (length(Streams) == 1) 0 else c(0, head(Streams, -1) - tail(Streams, -1)), by=c(setdiff(byCols, "month"), "O_v_S")] DT.rev2[kvals]