[R] Help plase with simple loop

David Winsemius dwinsemius at comcast.net
Sun Mar 15 15:35:40 CET 2009


I don't think you have gotten the basic idea of functions in R. Those  
functions would return only the value of the last evaluated  
expression, e.g. (1+par[1]) in the case of f1, but most of the code  
appears to have no effect. See this simple example:

 > x1 <- 4
 > f1 <- function(x) x1 <- x
 > f1(1)
 > x1
[1] 4  # nothing happens to the x1 in the enclosing environment,; the  
one inside the function is gone.

The "x1" inside the function "f1" is local to the function and has no  
persistency after the evaluations are completed..

f4 <- function(par) {1+par[4]} # would have same effect as your f1
 > f4(1:4)
[1] 5

You should tell us what you actually want to do. You generally call  
functions with a particular set of arguments for which you have  
provided no examples and then expect those functions to return some  
sort of object which you have also not defined.

-- 
David Winsemius
On Mar 15, 2009, at 9:36 AM, Axel Urbiz wrote:

> Dear All,
>
> I’m  a new R user.  How can I write code below more efficiently  
> (using a
> loop for example)?
>
> f1 <-function(par){x1 <- par[1]; x2 <- par[2];x3 <- par[3] ; x4 <-  
> par[4]
> ; (1+x1)}
>
> f2 <-function(par){x1 <- par[1]; x2 <- par[2];x3 <- par[3] ; x4 <-  
> par[4]
> ;(1+x2)}
>
> f3 <-function(par){x1 <- par[1]; x2 <- par[2];x3 <- par[3] ; x4 <-  
> par[4]
> ; (1+x3)}
>
> f4 <-function(par){x1 <- par[1]; x2 <- par[2];x3 <- par[3] ; x4 <-  
> par[4] ;
> (1+x4)}
> Each function has four parameters independently on whether a specific
> variable is explicitly in the function or not.
>
> Many thanks for your help!
>
> Axel.
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list