contour - An Error in R: When I try to apply outer function: -


here code: step1: define inverse function use later

inverse = function (f, lower = -100, upper = 100) {   function (y) uniroot((function (x) f(x) - y), lower = lower, upper = upper)[1] } 

step2: here functions , inverse:

f1<-function(x,m1,l,s1,s2){l*pnorm((x-m1)/s1)+(1-l)*pnorm((x+m1)/s2)}  f1_inverse = inverse(function(x) f1(x,1,0.1,2,1) , -100, 100)  f2<-function(x,m2,l,s1,s2){l*pnorm((x-m2)/s1)+(1-l)*pnorm((x+m2)/s2)}  f2_inverse = inverse(function(x) f1(x,1,0.1,2,1) , -100, 100) 

step3: here final function combines above functions (i sure function correct):

copwnorm<-function(x,y,l,mu1,mu2,sd1,sd2) {   (l*dnorm(((f1_inverse(pnorm(x))$root-mu1)/sd1))*     dnorm(((f2_inverse(pnorm(y))$root-mu2)/sd1))) } 

step4: want create contour plot function in stepenter code here3:

x<-seq(-2,2,0.1) y<-seq(-2,2,0.1)  z<-outer(x,y,copwnorm)  contour(x,y,z,xlab="x",ylab="y",nlevels=15) 

here problem comes in, when tried apply function outer(x,y,copwnorm), gives me error:invalid function value in 'zeroin'. may ask how solve problem?

i believe commom misconception assume outer(x, y, fun) calls function parameter (fun) once each required pair x[i] , y[j]. actually, outer calls fun once, after creating possible pairs, combining every element of x every element of y, in manner similar function expand.grid.

i'll show example: consider function, wrapper product , print message every time it's called:

f <- function(x,y) {     cat("f called arguments: x =", capture.output(dput(x)), "y =", capture.output(dput(y)), "\n")      x*y } 

this function "naturally" vectorized, can call vector arguments:

> f(c(1,2), c(3,4)) f called arguments: x = c(1, 2) y = c(3, 4)  [1] 3 8 

using outer:

> outer(c(1,2), c(3,4), f) f called arguments: x = c(1, 2, 1, 2) y = c(3, 3, 4, 4)       [,1] [,2] [1,]    3    4 [2,]    6    8 

notice combinations generated.

if can't guarantee function can handle vector arguments, there simple trick ensure function gets called once each pair in combinations: vectorize. creates function calls original function once each element in arguments:

> vectorize(f)(c(1,2),c(3,4)) f called arguments: x = 1 y = 3  f called arguments: x = 2 y = 4  [1] 3 8 

so can make "safe" outer it:

> outer(c(1,2), c(3,4), vectorize(f)) f called arguments: x = 1 y = 3  f called arguments: x = 2 y = 3  f called arguments: x = 1 y = 4  f called arguments: x = 2 y = 4       [,1] [,2] [1,]    3    4 [2,]    6    8 

in case, results same because f written in vectorized way, i.e., because "*" vectorized. if function not written in mind, using directly in outer may fail or (worse) may give wrong results.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -