[R] Environments

Bill.Venables at csiro.au Bill.Venables at csiro.au
Thu Apr 2 14:04:38 CEST 2009


What you are trying to do is make R behave like a macro language, which is not a good idea at all.  Better to use R as it was designed to be used rather than make it behave like something it wasn't.

It also follows that trying to do this is going to be tricky.  Here is one way:

RENAME <- function(table, from, to) {
  X <- deparse(substitute(table))
  k <- which(names(table) == from)
  names(table)[k] <- to
  assign(X, table, pos = parent.frame())
  invisible(table)
}

### at test

> x <- structure(1:4, names = c("A","B","C","D"))
> x
A B C D 
1 2 3 4 
> RENAME(x, "C", "Z")
> x
A B Z D 
1 2 3 4 
> 

-- but don't do it, there's a sport!

Your solution would work if you were just able to use it in an assignment

x <- rename(x, "C", "Z")

but your function could do with a little tidying up.


Bill Venables.
________________________________________
From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] On Behalf Of Philip Whittall [Philip.whittall at detica.com]
Sent: 02 April 2009 19:31
To: r-help at r-project.org
Subject: [R] Environments

Dear List,

No doubt I am going around this the wrong way, and hopefully one of you
will be able to tell me how to go about it the right way.
I want to change the names of an object inside a function and have it
stay changed in the global environment. I can only
effect the change inside the function as follows ...

> x<-1:4;names(x)<-c("A","B","C","D")
> x
A B C D
1 2 3 4
> rename<-function(table, from,
to){names<-names(table);position<-sum((names==from)*1:length(names));nam
es(table)[position]<-to;table}
> rename(x,"C","Z")
A B Z D
1 2 3 4
> x
A B C D
1 2 3 4
>

I am running R version 2.8.0 on a windows XP platform,

Thanks in anticipation,

Philip



This message should be regarded as confidential. If you have received this email in error please notify the sender and destroy it immediately.
Statements of intent shall only become binding when confirmed in hard copy by an authorised signatory.  The contents of this email may relate to dealings with other companies within the Detica Group plc group of companies.

Detica Limited is registered in England under No: 1337451.

Registered offices: Surrey Research Park, Guildford, Surrey, GU2 7YP, England.



        [[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.




More information about the R-help mailing list