Sofie Seidenfaden
Sofie Seidenfaden

Reputation: 1

average weights in aggregated population

I have a probably very simple question, I hope you will be able to help me with. I have to compute weighted averages for proportion liberal in each american state. I have computed the 'raw' proportion liberal by this command:

liberal.state<-aggregate(liberal, by=list(state), mean ,na.rm=TRUE)
#liberal=binary variable

This works fine!

I have also a function of sample size pr. state:

sample.state<-aggregate(rid, list(state=state), length)
#rid=id for respondent

This works fine as well!

I want to weight the weighted averages of proportion liberal in each state. I use this formula:

N <- sample.state
p <- liberal.state
w.avg <-sum(N*p)/sum(N)

But I keep getting this error message:

Error in FUN(X[[1L]], ...) : 
  only defined on a data frame with all numeric variables
In addition: Warning message:
In Ops.factor(left, right) : ‘*’ not meaningful for factors

I hope one of you will be able to help me! Thank you in advance!

Best Sofie

Upvotes: 0

Views: 286

Answers (1)

bjoseph
bjoseph

Reputation: 2166

Your problem is that one of the 'columns' in your N and P variables is stored as a factor, and you cannot meaningfully divide factors. Below I construct a reproducible example using the iris dataset.

> data(iris)
> liberal.flowers<-aggregate(iris$Sepal.Length, by=list(iris$Species), mean ,na.rm=TRUE)
> sample.flowers<-aggregate(row.names(iris),list(iris$Species), length)
> 
> N <- sample.flowers
> p <- liberal.flowers
> w.avg <-sum(N*p)/sum(N)
Error in FUN(X[[1L]], ...) : 
  only defined on a data frame with all numeric variables
In addition: Warning message:
In Ops.factor(left, right) : ‘*’ not meaningful for factors

Let's look at what the objects look like:

liberal.flowers
         Group.1     x
    1     setosa 5.006
    2 versicolor 5.936
    3  virginica 6.588
sample.flowers
         Group.1  x
    1     setosa 50
    2 versicolor 50
    3  virginica 50

Your Group.1 variable is a factor.

str(sample.flowers)
'data.frame':   3 obs. of  2 variables:
 $ Group.1: Factor w/ 3 levels "setosa","versicolor",..: 1 2 3
 $ x      : int  50 50 50

merge.dat<-merge(sample.flowers,liberal.flowers,by="Group.1")
merge.dat
     Group.1 x.x   x.y
1     setosa  50 5.006
2 versicolor  50 5.936
3  virginica  50 6.588
N <- merge.dat[,2] #Column 2 length
P <- merge.dat[,3] #Column 3 mean
merge.dat$w.avg <-sum(N*P)/sum(N)
merge.dat
     Group.1 x.x   x.y    w.avg
1     setosa  50 5.006 5.843333
2 versicolor  50 5.936 5.843333
3  virginica  50 6.588 5.843333

Note your weighted average isn't returning what I believe you would like as all of the weighted averages are the same. I believe you would prefer the below.

merge.dat$w.avg <-N*P/sum(N)

Upvotes: 1

Related Questions