Hi, I have a data.frame a like this:> av1 v2 v3 v4 1 1 1 A X 2 2 2 A X 3 3 3 A X 4 4 4 B X 5 5 5 B X 6 6 6 C Y 7 7 7 C Y 8 8 8 C Y 9 9 9 D Y 10 10 10 D Y I want to get a weighted average for each combination of v3 and v4, using v1 as values and v2 as weights i.e., for A and X, the final result should be (1*1+2*2+3*3)/(1+2+3) not sure which function I should use in R ? thanks, -- Weiwei Shi, Ph.D "Did you always know?" "No, I did not. But I believed..." ---Matrix III
On 11/17/2005 6:25 PM, Weiwei Shi wrote:> Hi, > I have a data.frame a like this: > >>a > > v1 v2 v3 v4 > 1 1 1 A X > 2 2 2 A X > 3 3 3 A X > 4 4 4 B X > 5 5 5 B X > 6 6 6 C Y > 7 7 7 C Y > 8 8 8 C Y > 9 9 9 D Y > 10 10 10 D Y > > I want to get a weighted average for each combination of v3 and v4, > using v1 as values and v2 as weights i.e., > for A and X, the final result should be (1*1+2*2+3*3)/(1+2+3) > > not sure which function I should use in R ?Use by(). For example, by(a, list(a$v3, a$v4), function(subset) weighted.mean(subset$v1, subset$v2)) Duncan Murdoch
On 11/17/05, Weiwei Shi <helprhelp at gmail.com> wrote:> Hi, > I have a data.frame a like this: > > a > v1 v2 v3 v4 > 1 1 1 A X > 2 2 2 A X > 3 3 3 A X > 4 4 4 B X > 5 5 5 B X > 6 6 6 C Y > 7 7 7 C Y > 8 8 8 C Y > 9 9 9 D Y > 10 10 10 D Y > > I want to get a weighted average for each combination of v3 and v4, > using v1 as values and v2 as weights i.e., > for A and X, the final result should be (1*1+2*2+3*3)/(1+2+3) > > not sure which function I should use in R ?All our solutions will make use of this function f: f <- function(i) weighted.mean(a$v1[i], a$v2[i]) # Here are three solutions that only give combos # that are already present in the data: aggregate(rownames(a), a[,3:4], f) aggregate(1:nrow(a), a[,3:4], f) sapply(split(1:nrow(a), a[,3:4], drop = TRUE), f) # and here are two solutions that give all combos # returning results in different ways: tapply(1:nrow(a), a[,3:4], f) sapply(split(1:nrow(a), a[,3:4]), f) Aside: I found it strange that rownames only works in the first case.