I have a data frame as follows:
date Rank new_Weight c
2019-01-01 20 2 10
2019-01-01 30 5 10
2019-01-01 10 8 10
2019-02-02 3 10 60
2019-02-02 5 2 60
.... ... ....
I want to calculate the weighted average based on Rank and new weight I have applied the following code:
by(df, df$date,subset) function(x){
x<-df$rank*df$new_weight/sum(df$new_weigth)
}
and create a new column.
I wrote the following function and it works very well.
df<- df %>% group_by(date) %>% mutate(w=weighted.mean(rank,new_weight))
however I am wondering why the first function does not work.