[英]calculated weighted average in r based on two columns
我有一個數據框,如下所示:
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
.... ... ....
我想根據排名和新的權重來計算加權平均值,我已經應用了以下代碼:
by(df, df$date,subset) function(x){
x<-df$rank*df$new_weight/sum(df$new_weigth)
}
並創建一個新列。
我編寫了以下函數,並且效果很好。
df<- df %>% group_by(date) %>% mutate(w=weighted.mean(rank,new_weight))
但是我想知道為什么第一個功能不起作用。
這個樣本可以回答您的問題嗎?
date<-c(2017, 2017, 2018, 2019, 2018, 2019)
rank<-c(10, 12, 13, 11, 14, 15)
weight<- c(1.5, 1.1, 1.2, 1.3, 1.4, 1.7)
df<-data.frame(date, rank, weight)
df
df<- df %>% group_by(date) %>% mutate(w=weighted.mean(rank,new_weight))
您不需要任何功能即可;)
我認為by
您正在嘗試將x
引用為dataframe而不是df
。 此外,需要更改計算加權平均值的公式
by(df, df$date, function(x) sum(x$Rank * x$new_Weight)/sum(x$new_Weight))
#df$date: 2019-01-01
#[1] 18
#---------------------------------------------------------------------------------
#df$date: 2019-02-02
#[1] 3.333333
這與應用weighted.mean
相同
by(df, df$date, function(x) weighted.mean(x$Rank, x$new_Weight))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.