[R] understanding the FUNCTION function

David Winsemius dwinsemius at comcast.net
Thu Apr 26 21:57:57 CEST 2012


On Apr 26, 2012, at 3:40 PM, michaelyb wrote:

> David -
> My question to you may sound (actually, it really is) silly, but  
> please do
> take your time to answer it.
>
> What is the difference between:
> fac<-function(x){a<-1
>                for (i in 1:x){
>                 a<-a*i
>                  }a}
>
> and:
>
> fac<-function(x){a<-1
>                  for (i in 1:x){
>                  a<-a*i
>                  }
>                  a}

In R parsing, there is an implicit command separator performed by the  
end-of-line character. To get the first one to run without adding an  
end-of-line you can use a semi-colon:

fac<-function(x){a<-1
                for (i in 1:x){
                 a<-a*i
                  }; a}


Some people get annoyed when these are added unnecessarily, as may  
happen for SAS programmers who come over to R and are used to always  
using semicolons.


> I did try the first one, but I got an error message, so I thought I  
> was
> doing something wrong. However, once it finishes the loop, why the
> difference between the last lines?
-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list