Archive for Vectorize


Posted in R, Statistics with tags , , on February 21, 2011 by xi'an

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:
+   return(sum(X<x))

does 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<x does not make sense when both X and x are vectors. If one rewrites the code as


the function can be integrated

> integrate(Femp,-2,2)
1.877735 with absolute error < 5.6e-05

However, this kind of syntactic gymnastic can be avoided by a simple call to Vectorize.

> integrate(Vectorize(Femp),-2,2)
1.877735 with absolute error < 5.6e-05
%d bloggers like this: