Vectorize!
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Here is an email sent by one of my students a few days ago:
Do you know how to integrate a function with an “if”?
For instance:
>X=rnorm(100)
>Femp=function(x){
+ return(sum(X+}
>integrate(Femp,0,1)$valuedoes not work.
My reply was that the fundamental reason it does not work is that integrate (or curve for instance) computes the function in several points of a grid by calling the function on a vector x and the comparison X the function can be integrated However, this kind of syntactic gymnastic can be avoided by a simple call to Vectorize.
X=rnorm(100)
Femp=function(x){
return((apply(as.matrix(outer(X,x,"-")<0),2,sum))}
> integrate(Femp,-2,2)
1.877735 with absolute error < 5.6e-05
X=rnorm(100)
Femp=function(x){
return(sum(X<x))}
> integrate(Vectorize(Femp),-2,2)
1.877735 with absolute error < 5.6e-05
Filed under: R, Statistics Tagged: integrate, R, Vectorize
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.