2012-12-23 40 views
2

我想问一下,是否有一种功能将我们带入环境。 例如:搬入环境

# create two environments 
Env1 <- new.env() 
Env2 <- new.env() 

# assign one variable into each environment 
assign("v1", "1", envir = Env1) 
assign("v2", "2", envir = Env2) 

# In order to refer to the variable in Env2 I have to use Env2$v2, for example 
print(Env2$v2) 

# The question is if there is some function that sents us into Env2 
# so that when we refer to the variable in Env2 to use just v2, that is 
print(v2) 

谢谢大家

回答

2

根据你所说的“是指变量,” attach做到这一点的:

attach(Env2) 
print(v2) 
## [1] "2" 

detach() 
print(v2) 
## Error in print(v2) : object 'v2' not found 

试图修改的值是不同的故事,因为它附加在位置2.

+0

你是对的。非常感谢你 –

+0

如果我们尝试修改它? –

+1

你可以像上面那样用'assign'修改它。如果使用'<-'进行赋值,则将在当前环境中(位置1)创建一个具有相同名称的新变量。 –