Wagner Jorge
Wagner Jorge

Reputation: 43

Rename objects in environment r

I'd like to rename objects in environment r. For example,

y1 <- vector('list', 3)

x1 <- matrix(0, 3, 3)
x2 <- matrix(1, 3, 3)
x3 <- matrix(2, 3, 3)

y1[[1]] <- x1
y1[[2]] <- x2
y1[[3]] <- x3

y2 <- vector('list', 3)

y2[[1]] <- x1
y2[[2]] <- x2
y2[[3]] <- x3

y <- new.env()
y$y1 <- y1
y$y2 <- y2

names(y)

names(y) <- c('a', 'b')

I expected that the name of lists inside y was a and b, that is, names(y) equals c('a', 'b'),

Obs.: I can't rename manually the variables y1 and y2, I need to change them inside the environment.

Upvotes: 4

Views: 4764

Answers (3)

xm1
xm1

Reputation: 1765

Do you really need an environment, or a list could do the job? If so, you could rename the list items easily:

...
...
y=list()
y$y1 <- y1
y$y2 <- y2
names(y)=c('a','b')
names(y)
[1] "a" "b"

I have the opposite problem: getSymbols put the result in an environment and I changed it to a list to rename them:

acao
[1] "PETR4.SA" "VALE3.SA" "ITUB4.SA"
require(quantmod)
e1=new.env()
x=getSymbols(acao,env=e1) 
e1=as.list(e1)
names(e1)
[1] "ITUB4.SA" "VALE3.SA" "PETR4.SA"
names(e1)=sub('.SA$','',names(e1))
names(e1)
[1] "ITUB4" "VALE3" "PETR4"

Upvotes: 0

MrFlick
MrFlick

Reputation: 206167

R doesn't really have a built in operation to rename variables in any environment. YOu could write a simple helper function to do that.

env_rename <- function(e, new_names, old_names = names(e)) {
  stopifnot(length(new_names)==length(old_names)) 
  orig_val <- mget(old_names, envir=e)
  rm(list=old_names, envir=e)
  for(i in seq_along(old_names)) {
    assign(new_names[i], orig_val[[i]], envir=e)
  }
}

and call that with

env_rename(y, c("a","b"))

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545508

If you can’t assign them directly with the correct name, then the easiest is to replace the environment by a new one. If you absolutely need to preserve the environment (because it’s referenced elsewhere), you can replace its contents using the same trick:

objs = mget(ls(env), env)
rm(list = ls(env), envir = env)
list2env(setNames(objs, new_names), env)

The relevant part here is the last parameter to list2env: if you leave it off, this just creates a new environment. If you specify an existing environment, the names are added to that instead.

This code will leave hidden names (i.e. names starting with .) untouched — to change this, provide the all.names argument to ls, or use names.

Upvotes: 4

Related Questions