简体   繁体   English

基于两列计算r中的加权平均值

[英]calculated weighted average in r based on two columns

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. 但是我想知道为什么第一个功能不起作用。

Is this sample answer your question ? 这个样本可以回答您的问题吗?

 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))

You don't need any function to do this ;) 您不需要任何功能即可;)

I think with by what you are trying to do is reference x as dataframe and not df . 我认为by您正在尝试将x引用为dataframe而不是df Also the formula to calculate weighted mean needs to be changed 此外,需要更改计算加权平均值的公式

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

which is same as applying weighted.mean 这与应用weighted.mean相同

by(df, df$date, function(x) weighted.mean(x$Rank, x$new_Weight))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM