I am using integrate function (in R) to numerically compute integrals. I have an univariate function with one argument f(x,a) like this (just for example purpose):
test = function(x,a) 1/sqrt(2*pi)*exp(-(x-a)^2/2)
I want to define new univariate function, which is a function of a after integrate the above function:
testa = function(a) integrate(test,0,Inf,a=a)$value #this works
Now my question is that is it possible to use integrate function on function testa ? For example:
integrate(testa,0,1) # not working
I tried and it is not working (got error message evaluation of function gave a result of wrong length). I already know that one can apply multivariate integration procedure directly on test (for example use adaptIntegrate function from cubature package). But that is not my purpose!
So does anyone know how to apply successively integrate function like the example above? Or confirm that this is not permitted in R?
Thank in advance
integrate needs a vectorized function. You can use Vectorize:
integrate(Vectorize(testa),0,1)
#0.6843731905 with absolute error < 0.00000000000022
Disclaimer: I haven't checked the result for correctness.
Related
I am trying to use trapezoid integration, and as a result integrating the survival function(1-F(x)) of a mixture of lognormal distribution, using the code below:
for(i in 1: nrow(mydf)){
mydf$Ex[i]<- trapzfun(function(x){(1-pnorm((log(x)-mydf$mu1[i])/mydf$sd1[i]))*mydf$pmix1[i]+(1-pnorm((log(x)-mydf$mu2[i])/mydf$sd2[i]))*mydf$pmix2[i]},a=0,b=1)
mu1,sd1,pmix1 is my mean,std in logscale. pmix1 and pmix2 are mixing proportions.
While this is running well, it is taking about 3-5 hours of run time.
I guess "for loops" are not a good method, and I am pretty new to R. I did try to use an apply function:
mixture<- function(x){
trapzfun(function(x){(1-plnorm(x,mydf$mu1,mydf$sd1))*mydf$pmix1+(1-plnorm(x,mydf$mu2,mydf$sd2))*mydf$pmix2},a=0,b=1)
}
[Note the similarity with plnorm and pnorm using the transformation I applied]
mydf$Ex_1<- apply(mydf,1,mixture)
It is returning list(value = c(0.055257000747731, 0.055257000747731, 0.00.....
Can you please help me on this problem!
Can anyone help me understand what a wrapper function in r is? I would really appreciate if you could explain it with the help of examples on building one's own wrapper function and when to use one.
Thanks in advance.
Say I want to use mean() but I want to set some default arguments and my usecase doesn't allow me to add additional arguments when I'm actually calling mean().
I could create a wrapper function:
mean_noNA <- function(x) {
return(mean(x, na.rm = T))
}
mean_noNA is a wrapper for mean() where we have set na.rm to TRUE.
Now we could use mean_noNA(x) the same as mean(x, na.rm = T).
Wrapper functions occur in any programming language, and they just mean that you are "wrapping" one function inside another function that alters how it works in some useful way. When we refer to a "wrapper" function we mean a function that the main purpose of the function is to call some internal function; there may be some alteration or additional computation in the wrapper, but this is sufficiently minor that the original function constitutes the bulk of the computation.
As an example, consider the following wrapper function for the log function in R. One of the drawbacks of the original function is that it does not work properly for negative numeric inputs (it gives NaN with a warning message). We can remedy this by creating a "wrapper" function that turns it into the complex logarithm:
Log <- function(x, base = exp(1)) {
LOG <- base::log(as.complex(x), base = base)
if (all(Im(LOG) == 0)) { LOG <- Re(LOG) }
LOG }
The function Log is a "wrapper" for log that adjusts it so that it will now accept numeric or complex inputs, including negative numeric inputs. In the event that it receives a non-negative numeric or a complex input it gives the same output the original log function. However, if it is given a negative numeric input it gives the complex output that should be returned by the complex logarithm.
Currently I'm working on a R project which includes following code.
vec <- 1:25
fib <- function(x)
{ if (x==0) return (0)
if (x==1) return (1)
if (x==2) return(2)
return(fib(x-1)+fib(x-2))
}
lapply(vec,fib)
I just want to know that, how does R compute the fibonacci function in a code like this? More simply, when it comes to number 25 in vector "vec" does R compute the whole function, or can R compute the fib(25) using the values of fib(24) and fib(23) since they have been computed already?
It will compute all the recursive values one by one by default, but you can use an external package like memoise to cache previous values, or do it yourself. Have a look at the following blog which shows this using a Fibonacci function as well.
I have this function
ANN<-function (x,y){
DV<-rep(c(0:1),5)
X1<-c(1:10)
X2<-c(2:11)
ANN<-neuralnet(x~y,hidden=10,algorithm='rprop+')
return(ANN)
}
I need the function run like
formula=X1+X2
ANN(DV,formula)
and get result of the function. So the problem is to say the function USE the object which was created during the run of function. I need to run trough lapply more combinations of x,y, so I need it this way. Any advices how to achieve it? Thanks
I've edited my answer, this still works for me. Does it work for you? Can you be specific about what sort of errors you are getting?
New response:
ANN<-function (y){
X1<-c(1:10)
DV<-rep(c(0:1),5)
X2<-c(2:11)
dat <- data.frame(X1,X2)
ANN<-neuralnet(DV ~y,hidden=10,algorithm='rprop+',data=dat)
return(ANN)
}
formula<-X1+X2
ANN(formula)
If you want so specify the two parts of the formula separately, you should still pass them as formulas.
library(neuralnet)
ANN<-function (x,y){
DV<-rep(c(0:1),5)
X1<-c(1:10)
X2<-c(2:11)
formula<-update(x,y)
ANN<-neuralnet(formula,data=data.frame(DV,X1,X2),
hidden=10,algorithm='rprop+')
return(ANN)
}
ANN(DV~., ~X1+X2)
And assuming you're using neuralnet() from the neuralnet library, it seems the data= is required so you'll need to pass in a data.frame with those columns.
Formulas as special because they are not evaluated unless explicitly requested to do so. This is different than just using a symbol, where as soon as you use it is evaluated to something in the proper frame. This means there's a big difference between DV (a "name") and DV~. (a formula). The latter is safer for passing around to functions and evaluating in a different context. Things get much trickier with symbols/names.
I came across the editorial review of the book The Art of R Programming, and found this
The Art of R Programming takes you on a guided tour of software development with R, from basic types and data structures to advanced topics like closures, recursion, and anonymous functions
I immediately became fascinated by the idea of anonymous functions, something I had come across in Python in the form of lambda functions but could not make the connection in the R language.
I searched in the R manual and found this
Generally functions are assigned to symbols but they don't need to be. The value returned by the call to function is a function. If this is not given a name it is referred to as an anonymous function. Anonymous functions are most frequently used as arguments other functions such as the apply family or outer.
These things for a not-very-long-time programmer like me are "quirky" in a very interesting sort of way.
Where can I find more of these for R (without having to buy a book) ?
Thank you for sharing your suggestions
Functions don't have names in R. Whether you happen to put a function into a variable or not is not a property of the function itself so there does not exist two sorts of functions: anonymous and named. The best we can do is to agree to call a function which has never been assigned to a variable anonymous.
A function f can be regarded as a triple consisting of its formal arguments, its body and its environment accessible individually via formals(f), body(f) and environment(f). The name is not any part of that triple. See the function objects part of the language definition manual.
Note that if we want a function to call itself then we can use Recall to avoid knowing whether or not the function was assigned to a variable. The alternative is that the function body must know that the function has been assigned to a particular variable and what the name of that variable is. That is, if the function is assigned to variable f, say, then the body can refer to f in order to call itself. Recall is limited to self-calling functions. If we have two functions which mutually call each other then a counterpart to Recall does not exist -- each function must name the other which means that each function must have been assigned to a variable and each function body must know the variable name that the other function was assigned to.
There's not a lot to say about anonymous functions in R. Unlike Python, where lambda functions require special syntax, in R an anonymous function is simply a function without a name.
For example:
function(x,y) { x+y }
whereas a normal, named, function would be
add <- function(x,y) { x+y }
Functions are first-class objects, so you can pass them (regardless of whether they're anonymous) as arguments to other functions. Examples of functions that take other functions as arguments include apply, lapply and sapply.
Get Patrick Burns' "The R Inferno" at his site
There are several good web sites with basic introductions to R usage.
I also like Zoonekynd's manual
Great answers about style so far. Here's an answer about a typical use of anonymous functions in R:
# Make some data up
my.list <- list()
for( i in seq(100) ) {
my.list[[i]] <- lm( runif(10) ~ runif(10) )
}
# Do something with the data
sapply( my.list, function(x) x$qr$rank )
We could have named the function, but for simple data extractions and so forth it's really handy not to have to.