A question that has come up a few times on r-help is how to rename columns
of a data.frame.  There are several ways to do this by hand (see the list
archives).  There is also a 'rename' function in the reshape package.

I often use the 'transform' function shortly after reading in a data file
and wanted to have a renaming function that has a syntax consistent with the
'transform' function (unlike 'rename', whose arguments have a reverse syntax
compared to 'transform').

Here is my attempt at a rename function similar to 'transform'.
Improvements are welcome.

ren <- function(`_data`, ...){
  # Influenced by transform.data.frame
  e <- unlist(list(...))
  inx <- match(e, names(`_data`))
  if(any(is.na(inx)))
    stop("Couldn't find these columns in the data: ",
         paste(as.vector(e)[is.na(inx)], collapse=" ") )
  names(`_data`)[inx] <- names(e)
  return(`_data`)
}

d0 <- data.frame(Year = c(2009, 2009, 2009),
                 Mst = c(27.9, 28.9, 31.0),
                 Yield = c(110, 180.1, 25))
ren(d0, yield='Yield')
ren(d0, 'yield'='Yield')
ren(d0, yield='Yield', year='Year')
ren(d0, yield='Yield', mst='Mst')
ren(d0, yield='YIELD', mst='MST') # Error caught.
# ren(d0, yield=Yield, year=Year)  # Fails.  Not caught.  Might be nice to
allow this syntax.


-- 
Kevin Wright

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to