Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set column names to lower case for multiple dataframes?

Tags:

r

apply

I have a set of dataframes with the same column headings, except that some of the column names are in upper case and some are in lower case. I want to convert all the column names to lowercase so that I can make one big dataframe of everything.

I can't seem to get colnames() to work in any loop or apply I write. With:

#create dfs
df1<-data.frame("A" = 1:10, "B" = 2:11)
df2<-data.frame("a" = 3:12, "b" = 4:13)
df3<-data.frame("a" = 5:14, "b" = 6:15)
#I have many more dfs in my actual data

#make list of dfs, define lowercasing function, apply across df list
dfs<-ls(pattern = "df")
lowercols<-function(df){colnames(get(df))<-tolower(colnames(get(df)))}
lapply(dfs, lowercols)

I get the following error:

Error in colnames(get(df)) <- tolower(colnames(get(df))) : 
  could not find function "get<-"

How do I change all my dataframes to have lowercase column names?

like image 855
William Gunn Avatar asked Apr 15 '12 22:04

William Gunn


1 Answers

The following should work:

dfList <- lapply(lapply(dfs,get),function(x) {colnames(x) <- tolower(colnames(x));x})

Problems like this generally stem from the fact that you haven't placed all your data frames in a single data structure, and then are forced to use something awkward, like get.

Not that in my code, I use lapply and get to actually create a single list of data frames first, and then alter their colnames.

You should also be aware that your lowercols function is rather un-R like. R functions generally aren't called in such a way that they return nothing, but have side effects. If you try to write functions that way (which is possible) you will probably make your life difficult and have scoping issues. Note that in my second lapply I explicitly return the modified data frame.

like image 68
joran Avatar answered Sep 21 '22 15:09

joran