[R] Problem with retrieving updated variables after attach()

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Tue Feb 10 13:01:53 CET 2009


attach provides a copy of rather than aliases to the variables within a
data frame.

d = data.frame(x=0)
attach(d)

x
# 0, from the attached copy of d

x = 1
x
# 1, from the global anvironment
d$x
# 0, from d

x <<- 2
x
# 1, from the global environment
d$x
# 0, from d
get('x', pos=2)
# 2, from the attached copy of d

rm(x)
x
# 2, from the attached copy of d

vQ  



David Croll wrote:
> Hello,
>
> suppose I have a data frame:
>
>   
>> mat
>>     
>  id age
> 1 NA  NA
> 2 NA  NA
> 3 NA  NA
> 4 NA  NA
> 5 NA  NA
>
> Then I attach the data frame:
>
>   
>> attach(mat)
>>     
>
> I assign some new values...
>
>   
>> id <<- sample(100,5)
>> age <<- rnorm(5,mean=30)
>>     
>
> Then I want to create a new data frame from the variables id and age which still are attached to position 2 of the R environment...
>
>   
>> new_mat <- data.frame(ls(pos=2)) # I want to rescue ALL variables that were created by attach(mat)
>>     
>
>   
>> new_mat
>>     
>  ls.pos...2.
> 1         age
> 2          id
>
> But this leads to a bogus object... how can I rescue the updated id and age values into new_mat?
>




More information about the R-help mailing list