R: How do you algebraically cancel the weighted value?
Let's say I have the following values:
ue <- c(0.1784545, 0.2248318, 0.2561000, 0.2722773, 0.2629545, 0.2797364 0.2294227)
ff <- c(679, 631, 588, 514, 380, 192 , 60)
r <- c(0.6167, 0.8099, 0.9902, 1.0767, 1.1359, 1.2550, 1.6187)
I want to solve the following algebraic equation:
weighted.mean((1-(ue+x)*r), ff) = .58498
Where I want to decide for x
. In other words, how much do I need to increase ue in order to have a weighted average of 1 minus the product ue*r
and ff
equal to .58498.
I can approximate this answer with a for loop, but I couldn't figure out how to do it algebraically.
source to share
This will do the job:
> ue <- c(0.1784545, 0.2248318, 0.2561000, 0.2722773, 0.2629545, 0.2797364, 0.2294227)
> ff <- c(679, 631, 588, 514, 380, 192 , 60)
> r <- c(0.6167, 0.8099, 0.9902, 1.0767, 1.1359, 1.2550, 1.6187)
> f <- function(x) (weighted.mean((1-(ue+x)*r), ff) - .58498)
> uniroot(f, lower=-100000000, upper=100000000)$root
[1] 0.2012965
Just make sure you specify lower
and upper
appropriately (based on your knowledge of the problem) to ensure that the root is within the range.
If you don't, it will throw an error:
> uniroot(f, lower=50, upper=100000000)$root
Error in uniroot(f, lower = 50, upper = 1e+08) :
f() values at end points not of opposite sign
source to share
If you just write an equation and do the math, it shouldn't be hard to find the following expression for x
:
((1-.58498) * sum(ff) - sum(ff*r*ue)) / sum(ff*r)
# [1] 0.2012965
Below are the main calculation steps, written using style R
. (These are not lines of code to accomplish, just a quick explanation.)
weighted.mean((1-(ue+x)*r), ff) == .58498
sum(ff * (1 - (ue+x)*r)) == .58498 * sum(ff)
sum(ff) - sum(ff*(ue+x)*r) == .58498 * sum(ff)
sum(ff*(ue+x)*r) == (1-.58498) * sum(ff)
sum(ff*ue*r) + x*sum(ff*r) == (1-.58498) * sum(ff)
Hence the result is: x == ((1-.58498) * sum(ff) - sum(ff*r*ue)) / sum(ff*r)
source to share