Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(rootSolve)
- d <- read.table(text="indx rate n d
- 1 0.12 158 14
- 2 0.095 135 9
- 3 0.057 123 4
- 4 0.033 115 5
- 5 0.019 90 4", header=T)
- d$real <- with(d, d/n)
- opt <- d[ ,c("rate","real", "n")]
- # this is close to the correct solution!
- scaler <- apply(opt, 1, function(z) uniroot.all(
- function(alpha) z[2] - (1 / (1 + alpha * ( (1 - z[1]) / z[1] )) ), interval = c(0,10)))
- # check for solution (not fully correct!)
- round(crossprod(scaler * opt$real, opt$n)/sum(opt$n), 3) == round(crossprod(round(opt$rate, 3), opt$n)/sum(opt$n), 3)
- # using optim() - completely wrong results
- infun <- function(data, alpha){ l <- with(data,
- ( rate - (1 / ( 1 + alpha[1] * ( (1 - real)/real ))) )); return( -sum( l ) ) }
- opt_out <- optim(c(0,0), infun, data=opt, method = "BFGS", hessian = TRUE)
- with(opt, (1 / ( 1 + opt_out$par[1] * ( (1 - real)/real ))))
Add Comment
Please, Sign In to add comment