I’m trying to create a script that will loop through some data frames and change their column names to lowercase.
firmNames <- c("file1","file2","file3","file4","file5")
for(i in 1:length(firmNames)){
fileName <- paste("data/",firmNames[i],".RData",sep="")
load(fileName)
upper <- names(get(firmNames[i]))
lower <- tolower(upper) # transforms to lower case
names(get(firmNames[i])) <- lower # This is the offending line
save(get(firmNames[i]), file = fileName)
}
This causes a syntax error:
Error in names(get(firmNames[i])) <- lower :
could not find function "get<-"
If I use assign, it still fails:
Error in save(get(firmNames[i]), file = fileName) :
object ‘get(firmNames[i])’ not found
In addition: Warning message:
In assign(names(get(firmNames[i])), lower) :
only the first element is used as variable name
Strangely, printing names(get(firmNames[i])) displays perfectly, as does lower. They are both of mode character. What am I missing?
A straightforward, readable, and sanity-preserving solution is to assign the
data.frameyou want to modify to a temporary object (here namedX). Work on that, and when you’ve got it in shape, overwrite the original object with the correctly modified one: