Message-ID: <BL0PR01MB4036C50C9F934D49026D6592FABD9@BL0PR01MB4036.prod.exchangelabs.com>
Date: 2022-07-01T11:07:37Z
From: Naresh Gurbuxani
Subject: split apply on multiple variables
I am looking for a more general solution to below exercise.
Thanks,
Naresh
library(plyr)
mydf <- data.frame(
date = rep(seq.Date(from = as.Date("2022-06-01"), by = 1, length.out =
10), 4),
account = c(rep("ABC", 20), rep("XYZ", 20)),
client = c(rep("P", 10), rep("Q", 10), rep("R", 10), rep("S", 10)),
profit = round(runif(40, 2, 5), 2), sales = round(runif(40, 10, 20), 2))
mydf.split <- split(mydf, mydf$account)
# if there are 10 variables like sales, profit, etc., need 10 lines
myres <- lapply(mydf.split, function(df) {
sales.ts <- aggregate(sales ~ date, FUN = sum, data = df) #one step for both?
profit.ts <- aggregate(profit ~ date, FUN = sum, data = df)
merge(profit.ts, sales.ts, by = "date")})
myres.df <- ldply(myres)