[R] using get() in assign()

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Dec 29 10:03:44 CET 2004


thomas hills <thills at mail.utexas.edu> writes:

> I'm trying to rename the columns in a list of data.frames using the 
> following...
> 
> for(i in 1:length(filenames)) {
> assign(names(get(filenames[i])), c("name", "infood", "time") ) }
> 
> R returns no errors, but the names are unchanged in the data.frames.
> 
> The original names were things like
> 
>  > names(get(filenames[2]))
> [1] "Tc45w4.V1" "Tc45w4.V2" "Tc45w4.V3"
> 
> after the above procedure they are still those names.
> 
> Ideas appreciated.  Thanks.

assign() takes a character string as its first argument, so you
probably now have a variable called "Tc45w4.V1" (it's a semi-bug that
it doesn't barf when passed a character vector of length > 1). What
you seem to want is

for(i in 1:length(filenames)) {
  t <- get(filenames[i])
  names(t) <-  c("name", "infood", "time")
  assign(filenames[i], t)
}

It is easier with a list

for (i in seq(along=listoftables)) 
   names(listoftables[[i]]) <- c("name", "infood", "time")

but *not* "for (i in listoftables) names(i) <- ..." because you'd be
changing the names of a copy of the actual elements.

I suspect the jury is still out on whether it is good programming
practice to do 

listoftables <- lapply(listoftables, "names<-", c("name", "infood", "time"))

but it is tempting in cases like this. (The awkward bit is that for
performance reasons, assignment functions -- names<-, [<-, etc. --
might not leave their argument unchanged.)
 
-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list