[R] writing function

Ivan Calandra ivan.calandra at uni-hamburg.de
Thu May 20 18:20:38 CEST 2010


Hi,

the problem is not about the environment, but about the
     paste(c("tot", i), collapse = "")
which is not recognized as an object.
Maybe assign() could do the trick

You could also do it this way (though it's not exactly what you want, 
but it might be better):
toto <- function(x,y){
   tot <- vector(mode="list", length=(y-x+1))   ##create an empty list 
of correct length
   for (i in x:y) {
     tot[[i]] <- (i*2)   ##store each value into each element of the list
   }
   return(tot)  ##return the list
}

HTH,
Ivan




Le 5/20/2010 17:54, arnaud Gaboury a écrit :
> 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.
>
>    

-- 
Ivan CALANDRA
PhD Student
University of Hamburg
Biozentrum Grindel und Zoologisches Museum
Abt. Säugetiere
Martin-Luther-King-Platz 3
D-20146 Hamburg, GERMANY
+49(0)40 42838 6231
ivan.calandra at uni-hamburg.de

**********
http://www.for771.uni-bonn.de
http://webapp5.rrz.uni-hamburg.de/mammals/eng/mitarbeiter.php



More information about the R-help mailing list