Skip to content
Back to formatted view

Raw Message

Message-ID: <F8A97883-BCA6-441F-84BB-2B16610F4D62@comcast.net>
Date: 2009-02-21T02:27:44Z
From: David Winsemius
Subject: how to add names to an object created using assign
In-Reply-To: <A5C9C326-7183-499C-B630-E64AC86910CE@gmail.com>

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.