[R] using 'sum' function in writing a function

Dieter Menne dieter.menne at menne-biomed.de
Mon Apr 10 11:06:04 CEST 2006


 <skim033 <at> student.ucr.edu> writes:

> 
> 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.

Looks like you are infected from other programming languages where in a 
function foo you must do a foo = ... to assign the return value. In R, this is 
a no-no, giving some mind-twisting recursion. And don't use c as a variable 
name. And parameters in sum() are comma separated, sum(c+x) is redundant. 

f<-function(x){
  c1 <- c(-1,0,1)
  sum(c1,c1)
}

f(12)

Dieter




More information about the R-help mailing list