[R] help creating a simple function to rename columns

David Winsemius dwinsemius at comcast.net
Mon Oct 21 21:23:25 CEST 2013

On Oct 21, 2013, at 11:45 AM, Carl Witthoft wrote:

> Steve E. wrote
>> Hi R users,
>> I am having some trouble with a very simple function that I hope that you
>> might be able to help me with (and, really, to shed some light on how
>> functions work generally). I have a series of very small 2-column data
>> frames of which I need to change the column names. A simple command such
>> as this one below works just fine on any given data frame:
>> colnames(DF) <- c("newname1","newname2")
>> However, I have to do this for numerous files and would like to address it
>> with a function for easier processing but when I put the above in a
>> function like this: 
>> cnames <- function(DF) {colnames(DF) <- c("newname1","newname2")}
>> the function returns a list of the column names instead of the modified
>> data frame (e.g., DF <- cnames(DF) returns the list
>> c("newname1","newname2") instead of a data frame with the desired column
>> names).
> 1) You've confused what a function *returns* with what goes on inside.  Your
> function quite correctly returns the result of the last command, which in
> this case is  c('newname1','newname2') .
> 2) Anything you do *inside* a function persists only in that environment. 
> What that means is that your "DF" inside the function is not your "DF" in
> your working environment, so nothing you do (with exceptions not to be gone
> into here) will change the actual matrix.
> An easier way: 
> alldf<-list(df1,df2,df3) # for however many little dfs you have
> for(j in 1:length(alldf) )  colnames(alldf[[j]])<- c("newname1","newname2")  
> I suspect there are cleaner tools in the *apply function  set (or the
> data.frame package).


In such an instance , you might try using either `names<-` or `colnames<-` with `lapply`.

alldf <- lapply(alldf, `names<-`, c("newname1","newname2")  )


David Winsemius
Alameda, CA, USA

More information about the R-help mailing list