简体   繁体   中英

call a function from a vector of given functions in R

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM