NEXUSAG
NEXUSAG

Reputation: 53

Looping through aggregate function in R

I am trying to use for loop in aggregate function, I was unable to assign X1, X2, X3 in aggregate function through for loop. I have created a fictitious example and have my code too

 year = cbind(rep(2000, 12), rep(2001, 12), rep(2002, 12))
 year = as.vector(as.matrix(year))
 month = cbind(seq(1:12), seq(1:12), seq(1:12))
 month = as.vector(as.matrix(month))
 X1 = rnorm(36, mean = 0, sd = 1)
 X2 = rnorm(36, mean = 2, sd = 1)
 X3 = rnorm(36, mean = 0, sd = 1)
 DF = data.frame(cbind(year, month, X1, X2, X3))

 for (i in 1:3) {
     bb_month = aggregate(as.symbol(sprintf('X%1.0f', i)) ~ month + year, DF , sum)
 }

Upvotes: 0

Views: 889

Answers (1)

Andrey Kolyadin
Andrey Kolyadin

Reputation: 1321

If I understood correctly, this should do the trick:

year <- rep(c(2000:2002), each = 12)
month <- rep(1:12, 3)
days <- rep("it's a day!", length(year)) #dummy var

X1 <- rnorm(36,  mean = 0,  sd = 1)
X2 <- rnorm(36,  mean = 2,  sd = 1)
X3 <- rnorm(36,  mean = 0,  sd = 1)

DF <- data.frame(year, month, days, X1, X2, X3)

aggregate(formula = . ~ year + month,
          data = DF[, names(DF) != "days"],
          FUN = sum)

EDIT: If you make similar calculation for X1-X3, there is probably a better way other than loop. But if you insist on doing it through loop:

for (i in 1:3) {
  fml <- as.formula(sprintf('X%i ~ month + year', i))
  bb_month <- aggregate(formula = fml,
                        data = DF, FUN = sum)
  ###Loop continues###
}

Upvotes: 1

Related Questions