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

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Tue Feb 10 14:18:26 CET 2009


Berwin A Turlach wrote:
> G'day David,
> 
> On Tue, 10 Feb 2009 13:23:50 +0100
> David Croll <david.croll at gmx.ch> wrote:
> 
>> Well, I knew that attach() only creates a copy of the variables in
>> the search path.
>>
>> What I wanted to ask was how to *retrieve* that copy...
>>
>>  > mat
>>  id age
>> 1 NA  NA
>> 2 NA  NA
>> 3 NA  NA
>> 4 NA  NA
>> 5 NA  NA  
>>
>>  > attach(mat)
>>
>>  > id <<- sample(100,5)
>>  > age <<- rnorm(5,mean=30)
>>
>> How can I make a new data frame out of the id and age that were
>> changed above?
> 
> R> new.df <- data.frame(id,age)
> 
> Or, perhaps more automatic:
> 
> R> new.df <- do.call(data.frame, sapply(ls(pos=2), as.name))
> 
> Is this what you are after?

There is also

as.data.frame(as.list(pos.to.env(2)))

or ...as.environment("mat")

I wouldn't recommend using <<- like that though; the consequences of
spelling mistakes on the LHS are a bit scary. If you must, consider

with(pos.to.env(2),{
  id <- sample(100,5)
  age <- rnorm(5,mean=30)
})

or better, modify before attach, using within() or transform().

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907




More information about the R-help mailing list