I have a data set like this:
df = read.table(text=' location total year TR TY TU TJ
A 822400 2010 0.09 0.09 0.07 0.07
A 822400 2010 0.13 0.08 0.08 0.06
B 822400 2010 0.18 0.07 0.10 0.05
B 565000 2009 0.05 0.05 0.04 0.04
B 565000 2009 0.07 0.04 0.04 0.03
A 565000 2008 0.10 0.03 0.05 0.02',header=T)
I want to compute the total-weighted mean of the two locations, by year and by properties(TR,TY,TU or TJ) using a function. To this end I wrote this:
total.weighted.mean <- function(df, properties, years){
dff<-filter(df, year==years)
res<-dff%>%
group_by(location) %>%
mutate(wt = weighted.mean(total, properties))
print(res)
}
total.weighted.mean( df, properties = "TR", years = 2009:2010)
But I get this error in function:
Error in weighted.mean.default(total, properties) :
'x' and 'w' must have the same length
and when i compute it out of the function, I get this:
location total year TR TY TU TJ wt
<chr> <int> <int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A 822400 2010 0.13 0.08 0.08 0.06 732310
2 B 565000 2009 0.07 0.04 0.04 0.03 732310
Is it correct to get the same wt for each location as we have different total values for different locations?
question from:
https://stackoverflow.com/questions/65641729/error-x-and-w-must-have-the-same-length-in-computing-weighted-mean-within 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…