[R] writing function

Joshua Wiley jwiley.psych at gmail.com
Thu May 20 21:14:09 CEST 2010


Hello,

I am guessing by my environment you mean the global environment (where
you normally assign things from the console).  It also looks like you
would like the results of your function call to be a set of new
objects created.  If that is what you are looking for, try:

toto <- function(x,y) {
for(i in x:y){
  assign(paste(c("tot",i),collapse=""), (i*2), envir=.GlobalEnv)
       }
}

toto(1,5) #creates 5 objects in the global environment, tot1, tot2, ..., tot5

HTH,

Josh

On Thu, May 20, 2010 at 8:54 AM, arnaud Gaboury
<arnaud.gaboury at gmail.com> wrote:
> Dear group,
>
> I am trying to write functions, but as a beginner, everything is not so
> obvious.
> Let's say I want the results in a list of elemts like this :
> tot1, tot2, etc
>
> Here is a function:
>
> toto <-
> function(x,y)
>
> {
>
> for(i in x:y){
>
> paste(c("tot",i),collapse="")<-(i*2)
>
> }
> }
>
> If I type this :
>>toto(1,5)
> I get this message error:
> Error in paste(c("tot", i), collapse = "") <- (i * 2) :
>  target of assignment expands to non-language object
>
> How can I write it to get the result I want (i.e tot1, tot2... with tot1=2,
> tot2=4...) in my environment?
>
> TY for any help
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Senior in Psychology
University of California, Riverside
http://www.joshuawiley.com/



More information about the R-help mailing list