[R] Function with multiple indices
cfchang3
cfchang3 at nccu.edu.tw
Tue Apr 17 16:20:12 CEST 2012
Hi,
I wrote a function which works for one group but not for multiple groups in several years. Could anyone help me out?
The dateset has 3 variables, year, group, and sales. I want to calculate the annual group median adjusted sales performance for observation i in group j and year yr, I do the following procedure.
For each yar,
1. exclude observation i from group j
2. calculate the sales median for group j without observation i and call it "med"
3. substract "med" from the sales of observation i to obtain the group median adjusted sales performance for observation i
The dataset, function, and questions are as follows.
x1 <- read.table(textConnection("YEAR GROUP SALES
1997 11 0.027
1997 11 0.001
1997 11 0.697
1997 11 0.047
1997 11 0.225
1998 11 0.025
1998 11 0.002
1998 11 0.001
1998 11 0.659
1998 11 0.037
1997 12 0.152
1997 12 0.025
1997 12 0.417
1997 12 0.081
1997 12 0.194
1997 12 0.069
1997 12 0.062
1998 12 0.146
1998 12 0.028
1998 12 0.437
1997 13 0.087
1997 13 0.008
1997 13 0.014
1997 13 0.010
1997 13 0.018
1997 13 0.002
1997 13 0.010
1997 13 0.079
1997 13 0.092
1997 13 0.118
1997 14 0.111
1997 14 0.013
1997 14 0.506
1997 14 0.333
1997 14 0.018
1997 14 0.017
1998 14 0.155
1998 14 0.018
1998 14 0.477
1998 14 0.312"), header=TRUE)
# The whole dataset
x1
# Data for the first group only
GROUP11 <- x1[1:10,]
GROUP11
# The function works for the first group in one year
perf = function(x) {
for (i in 1:nrow(x)) {
salesi <- x$SALES[i]
med <- median(x$SALES[-i])
print (salesi - med)
}
}
perf(GROUP11)
# Why the above funtion doesn't work in the following?
tapply(x1$SALES, list(x1$YEAR, x1$GROUP), perf)
aggregate(x1$SALES, by=list(x1$YEAR, x1$GROUP),FUN=perf)
Thanks!
Chingfu Chang
More information about the R-help
mailing list