[英]Rename objects in environment r
I'd like to rename objects in environment r.我想重命名环境 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')
,我预计y
中的列表名称是a
和b
,即names(y)
等于c('a', 'b')
,
Obs.: I can't rename manually the variables y1
and y2
, I need to change them inside the environment.观察:我无法手动重命名变量y1
和y2
,我需要在环境中更改它们。
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.这里的相关部分是list2env
的最后一个参数:如果你不使用它,这只会创建一个新环境。 If you specify an existing environment, the names are added to that instead.如果您指定现有环境,则会将名称添加到该环境中。
This code will leave hidden names (ie names starting with .
) untouched — to change this, provide the all.names
argument to ls
, or use names
.此代码将保留隐藏名称(即以.
开头的名称)不变 - 要更改此设置,请向ls
提供all.names
参数,或使用names
。
R doesn't really have a built in operation to rename variables in any environment. R 并没有真正的内置操作来重命名任何环境中的变量。 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"))
Do you really need an environment
, or a list
could do the job?你真的需要一个environment
,或者一个list
可以完成这项工作吗? 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:我有相反的问题: getSymbols
将结果放在一个environment
,我将其更改为一个list
以重命名它们:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.