I'm trying to write a generic function that calls different methods depending on the structure of the argument, but not the exact type of its contents. For example, the function 'nan2last' below works for a numeric vector but not for a vector of Date objects. Is there any way to make it work on any vector?
setGeneric("nan2last", function(x) { standardGeneric("nan2last") }) setMethod(nan2last, "vector", function(x) { naLocs <- (1:length(x))[is.na(x)] if (length(naLocs) == 0) return (x) naLocs <- naLocs[naLocs>1] for (i in 1:length(naLocs)) { x[naLocs[i]] <- x[naLocs[i]-1] } return(x) }) ## Works x <- 1:10; x[sample(10,3)] <- NA print(cbind(x, nan2last(x))) ## Doesn't work x <- seq(as.Date("2011-01-01"), as.Date("2011-01-31"), "days") x[sample(length(x), 5)] <- NA nan2last(x) Thanks. - Elliot ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.