[R] Function with multiple indices

Rui Barradas rui1174 at sapo.pt
Tue Apr 17 17:45:21 CEST 2012


Hello,

In your first call, perf(GROUP11), you're passing a data.frame, in the
'tapply' and 'aggregate'
you are passing a vector, x1$SALES, and the operator '$' is not valid.

> tapply(x1$SALES, list(x1$YEAR, x1$GROUP), perf)
Error in x$SALES : $ operator is invalid for atomic vectors

There's another thing, the function doesn't return a value, just prints
them.

See if this revision does what you want.

perf_b = function(x) {
      nr <- NROW(x)
      y <- numeric(nr)
      for (i in 1:nr) {
           salesi <- x$SALES[i]
           med <- median(x$SALES[-i])
           print(salesi - med)
           y[i] <- salesi - med
      }
      y
}

sapply(split(x1, list(x1$YEAR, x1$GROUP)), perf_b)

Then, 'unlist' the result.

Hope this helps,

Rui Barradas


--
View this message in context: http://r.789695.n4.nabble.com/Function-with-multiple-indices-tp4564907p4565175.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list