skim033 at student.ucr.edu
2006-Apr-10 01:30 UTC
[R] help on using sum in writng a function again
Hi, thanks for your reply. Here I would like to ask you again more directly. The following is what I had for now. The function to begin with is dnorm(theta+2*pi*j,0,1)*(pnorm(((2*pi*(k+1)-rho* (theta+2*pi*j)). Now, I wanted to sum it over k from -10000 to 10000. So, I wrote the following. f1<-function(theta,j){ aa<-seq(-10000,10000,lenght=20001) sum(dnorm(theta+2*pi*j,0,1)*(pnorm(((2*pi*(aa+1)-rho* (theta+2*pi*j)) } Next, I would like sum over j as (This is a way I thouhgt about computing a double sum) f2<-function(theta){ aa<-c(-1,0,1) sum(f(theta,aa)) } expecting f2 be a function of theta. Then, I wanted to plot f2 for theta from 0 to 2*pi. But, f2 (seq(0,2*pi,length=10)) is a scalar, not a vector with the dimension of 10x1. I would like to ask you how I can use rowSums with outer or some other method to correct my coding. I would like to thank you in advance. Sungsu. UC riverside.
Sorry, I replied to the wrong email. Here it is again: Try this where g is f summed over j and k for given scalars theta and rho and gv is g vectorized over theta. I have not checked this carefully so be sure you do: f <- function(theta = 0, rho = 0, j = 0, k = 0) dnorm(theta+2*pi*j,0,1)*pnorm(2*pi*(k+1)-rho*(theta+2*pi*j)) g <- function(theta = 0, j = 0, k = 0) sum(sapply(k, function(k) sum(f(theta, j = j, k = k)))) gv <- function(theta = 0, ...) sapply(theta, g, ...) x <- seq(0, pi, length = 100) plot(x, gv(x, j = -1:1, k = -1:1)) On 4/9/06, skim033 at student.ucr.edu <skim033 at student.ucr.edu> wrote:> Hi, thanks for your reply. > Here I would like to ask you again more directly. > The following is what I had for now. > The function to begin with is > dnorm(theta+2*pi*j,0,1)*(pnorm(((2*pi*(k+1)-rho* > (theta+2*pi*j)). > > Now, I wanted to sum it over k from -10000 to 10000. So, I > wrote the following. > f1<-function(theta,j){ > aa<-seq(-10000,10000,lenght=20001) > sum(dnorm(theta+2*pi*j,0,1)*(pnorm(((2*pi*(aa+1)-rho* > (theta+2*pi*j)) > } > > Next, I would like sum over j as > (This is a way I thouhgt about computing a double sum) > f2<-function(theta){ > aa<-c(-1,0,1) > sum(f(theta,aa)) > } > expecting f2 be a function of theta. > > Then, I wanted to plot f2 for theta from 0 to 2*pi. But, f2 > (seq(0,2*pi,length=10)) is a scalar, not a vector with the > dimension of 10x1. I would like to ask you how I can use > rowSums with outer or some other method to correct my coding. > > I would like to thank you in advance. > Sungsu. > UC riverside. > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html >