[R] help creating a simple function to rename columns

Carl Witthoft carl at witthoft.com
Mon Oct 21 20:45:36 CEST 2013


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).




--
View this message in context: http://r.789695.n4.nabble.com/help-creating-a-simple-function-to-rename-columns-tp4678719p4678726.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list