[R] Using functions that contain sums
Charles C. Berry
cberry at tajo.ucsd.edu
Fri Sep 26 23:15:42 CEST 2008
On Fri, 26 Sep 2008, Patrick M. Joyce wrote:
> Hello,
>
> I'm trying to perform an integration on a function that contains a sum.
> Similarly I'm hoping whatever acts as a fix will be good enough to aid in
> a 2nd case as well but I've already put in a work-around for that
> situation.
>
> My code example is here:
>
> watermelon=c(0,1,2,3)
>
> w<-function(x){
> sum(sin(x-watermelon))}
>
> integrate(function(x){w(x)},0,2)
>
> integrate(function(x){sin(x)+sin(x-1)+sin(x-2)+sin(x-3)},0,2)
>
> the first integral gives an error... the 2nd is what I should get for an
> answer for the first. Is there a way to get this to work the way that I
> desire?
Yes.
Do as you were asked:
*) Read the Posting Guide
Note this bit:
Do your homework before posting ...
* Read the online help for relevant functions (type ?functionname,
*) Then read the documentation for 'integrate'
Note this bit:
f must accept a vector of inputs and produce a vector
of function evaluations at those points. The Vectorize
function may be helpful to convert f to this form.
You may find the functions 'outer' and 'rowSums' to be helpful in crafting
a version of 'f' that produces vectorized output in this case.
HTH,
Chuck
>
> Any help is appreciated.
>
> Sincerely,
> Patrick Joyce
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
More information about the R-help
mailing list