[R] how to add names to an object created using assign

David Winsemius dwinsemius at comcast.net
Sat Feb 21 03:27:44 CET 2009


At this point, the function would only return the names because unless  
specified otherwise they return the result of the last evaluation. Add  
another line with just "a" and assign the results of the function to  
something:

 > testold=function(){
+ assign("a",c(1,2,3),env=.GlobalEnv)
+ names(a)=c("one","two","three")
+ }
 > a3 <- testold()
 > a3
[1] "one"   "two"   "three"


test=function(){
  assign("a",c(1,2,3),env=.GlobalEnv)  # I rather doubt the env  
assignment is needed
  names(a)=c("one","two","three");
  a
  }
  a2 <- test()
-----
 > a2
   one   two three
     1     2     3

QED;
David Winsemius

On Feb 20, 2009, at 6:32 PM, Fuchs Ira wrote:

> If I assign a variable in a function, as in:
>
> test=function(){
> assign("a",c(1,2,3),env=.GlobalEnv)
> }
>
> How can I do the equivalent of:
>
> names(a)=c("one","two","three")
>
> within the function?
>
> Merely adding the call to names does not work within the function as  
> it only affects a local variable:
>
> test=function(){
> assign("a",c(1,2,3),env=.GlobalEnv)
> names(a)=c("one","two","three")
> }
>
> ______________________________________________
> 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.




More information about the R-help mailing list