简体   繁体   中英

Solve equation with datatable in R

I am working with a large dataset in R using data table. I need to solve an equation and find the value of x in the expression:

data[,mean(pnorm(qnorm(var1)+x))]= 0.07

I have tried to use the function optimx using the following code:

library(optimx)
fnToFindRoot = function(x) {  
data[,mean(pnorm(qnorm(var1)+x))]}

rootSearch = optimx(0.07, fnToFindRoot)
str(rootSearch)
fnToFindRoot(rootSearch$par)

But the produced result is not correct. Can someone help me to solve this equation?

As it's only doing optimisation over one variable, optimize should work fine eg

fnToFindRoot = function(x, a=0.07) {  
  y <- data[,(mean(pnorm(qnorm(var1)+x)) - a)^2]
  print(sprintf("x: %s, y:%s", x, y))
  y
}
rootSearch = optimize(fnToFindRoot, interval=c(-5, 5), a=0.07)
fnToFindRoot(rootSearch$minimum)

The problem with the way you had it setup is that the optim function is always trying to minimise the objective. The way you were writing it, it was trying to minimise mean(pnorm(qnorm(var1)+x)) with 0.07 as the starting value of x . Instead, you want to get the objective as close to 0.07 as possible, so minimise (mean(pnorm(qnorm(var1)+x)) - a)^2 .

The interval controls the range of x that optimize can use

edit: I was using made up data, so check if rootSearch$minimum works for you. My made up data:

set.seed(1)
data <- data.table()
data[, var1 := runif(100, 0.04, 0.45)]
> fnToFindRoot(rootSearch$minimum)
[1] "x: -0.857685927870974, y:4.1043516952502e-13"
[1] 4.104352e-13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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