0

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!!
Community
  • 1
  • 1
theforestecologist
  • 4,667
  • 5
  • 54
  • 91
  • 1
    you need to return `dat` and save the results to a variable like any other function as [joran does](http://stackoverflow.com/questions/7680959/convert-type-of-multiple-columns-of-a-dataframe-at-once/7681273#7681273) for example – rawr Dec 05 '15 at 17:41
  • The first answer to the linked duplicate has a good example of the principle enunciated by rawr. – IRTFM Dec 05 '15 at 17:47

0 Answers0