skim033 at student.ucr.edu
2006-Apr-09 19:53 UTC
[R] help on using 'sum' in writng a function
Hi, I am writing a function that includes 'sum' function such as: f<-function(x){ c<-c(-1,0,1) f<-sum(c+x) } expecting f to be -1+x+0+x+1+x=3x. But I found out that f is sum(x). So, f is always a scalar, which means that f(c(0,1)) is not a vector as c(0,3), but 3(0+1)=3. I would like to ask you helping me in solving this problem. I would like to thank you in advance. Sungsu. UC riverside.
If c is c(c1, c2, c3) and x is c(x1, x2, x3) then c+x is (c1+x1, c2+x2, c3+x3) so sum(c+x) is c1+x1+c2+x2+c3+x3 = sum(c) + sum(x) What you were expecting is given by: rowSums(outer(1:4, c(-1,0,1), "+")) # gives c(3, 6, 9, 12) Review the Introduction to R manual and also look at ?outer and ?rowSums On 4/9/06, skim033 at student.ucr.edu <skim033 at student.ucr.edu> wrote:> Hi, I am writing a function that includes 'sum' function > such as: > f<-function(x){ > c<-c(-1,0,1) > f<-sum(c+x) > } > expecting f to be -1+x+0+x+1+x=3x. But I found out that f is > sum(x). So, f is always a scalar, which means that f(c(0,1)) > is not a vector as c(0,3), but 3(0+1)=3. I would like to ask > you helping me in solving this problem. 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 >