0

have the following function:

setTypes <- function(df2, ...) {
    fns <- as.list(substitute(list(...)))
    for(i in 1:length(df2)) {
        if(fns[i] == '') {
            next
        }
        df2[i,] <- fns[i](df2[i,])
    }
    return(df2)
}

want to do this:

test<-setTypes(sls,c('','as.Date','','','as.numeric','as.numeric'))

idea is to change the types of the fields in a data frame without having to do sls$field <- as.numeric(sls$field) for every field.

I had written a function like this that worked:

fn <- function(t) {
    return(t("55.55000"))
}

and the output is this:

> fn(as.numeric)
[1] 55.55

however, i can't figure out why either doing variable length argument as a list and calling it as list[index](input) doesn't work. or even passing a vector of functions like c(as.Date, as.numeric, as.character) and doing c[1]('2015-10-10') # as.Date('2015-10-10')

I am receiving the error 'attempt to apply non-function'.. I've also tried using call but to no avail. Help?

5SK5
  • 159
  • 1
  • 1
  • 15
  • I'm tempted to say this is a duplicate of [this](http://stackoverflow.com/q/7680959/324364) question... – joran Dec 03 '15 at 17:33
  • You get the error since your list of functions is a list of characters. Either skip the ' or use do.call – nist Dec 03 '15 at 17:36

1 Answers1

0

The problem is that class(c[1]) is a list use c[[1]] instead

Example code

v <- c(as.numeric,as.character)
v[[1]]("1")
v[[2]](1)

EDIT Your example should be:

setTypes <- function(df2, ...) {
  fns <- list(...)
  for(i in 1:NCOL(df2)) {
    if(is.function(fns[[i]])) {
      df2[,i] <- fns[[i]](df2[,i])
    }
  }
  return(df2)
}

df <- data.frame(v1 = c(1,2), v2 = c("1","2"))
setTypes(df,as.character,'',as.numeric)
bluefish
  • 395
  • 2
  • 13