I've seen a number of folks that have written loops or used different packages to change the class of numerous data.frame columns at once (see here, here, and here for SO examples), but I wanted to try my own function. The function works fine if I go line by line, but when I run the function nothing actually happens (i.e., the classes don't actually change). However, I don't get any errors either.
Any help in pointing out the issue would be appreciated!
The function:
class.changer <- function(col.names,dat,class.to) {
for(i in c(col.names)) {
dat[,i] <- eval(parse(text=paste0('as.',class.to,'(dat[,\'',i,'\'])')))
}
}
Example:
df <- data.frame(a=1:5,b=1:5)
str(df)
class.changer('a',df,'factor')
str(df) #alas, no change!!