jeudi 2 avril 2015

Modifying an Object Using Its Name in a String

I need an efficient way to convert to lowercase the column names of a number of data frames.


Suppose we have:



df1 <- data.frame(VAR1=c(1,2), VAR2=c("a", "b"))
df2 <- data.frame(VAR1=c(TRUE,FALSE), VAR2=c("foo", "bar"))


A simple way to get what I want is:



names(df1) <- tolower(names(df1))
names(df2) <- tolower(names(df2))


A little tedious if you have a large number of data frames, though.

I need something better.


I thought I could use get() in a loop:



my.files <- ls()
for(i in 1:2) names(get(my.files[i])) <- tolower(names(get(my.files[i])))


but it doesn't work. I couldn't find a solution using lapply() either.

Any suggestion to modify the column names of a large number of data frames without too much coding?


Aucun commentaire:

Enregistrer un commentaire