functions for array & vectors

Hi all,

It might be a silly question but I'll try to make it clear & to provide a toy example...
My aim is to develop some functions that apply either to array or to vector and in fine to wrap them in a package... What is the best approach? I've already read lot's of stuff (r-pkg...) but it is hard for me to figure out what would be the best strategy? Something like in the toy example (do what apply to array or vector and then make a type differentiation) or using S3 (and define "variation" of the function for each type of data)!

Sorry for the silly question, I've never developed functions for more than my own use and always for a predefined type of data.

foo <- function(data, lim = 0) {
  # apply to array or vector...
  tmp <- data - 3
  tmp[which(tmp < lim)] <- 0
  
  # need to specify the type
  if (is.array(data)) {
    apply(data, 1:2, cumsum) 
  } else {
    cumsum(data)
  } 
}

# init
test <- array(runif(48, 10, 30), dim = c(4, 4, 3))
res  <- foo(test)

all.equal(res[,1,1], foo(test[1,1,]))

thank you
cheers

1 Like