简体   繁体   中英

Need to pre-process input to functions

I am writing a package with a suite of functions that take objects fit to a model (eg, output from from "lmt", "lavaan", or "mirt" packages) and computes relevant indices based on those models.

The first thing EVERY function in this suite does is convert the input into a standardized form, so all of my functions look like this:

fooIndex <- function(x) {
  x <- standardizerFunction(x)
  # Now, compute the fooIndex
}

Here, standardizerFunction is an S3 generic function that has methods for all the supported input classes.

Is there a better way to accomplish this functionality than calling standardizerFunction inside of each of the functions computing indices?

EDIT: I just wanted to specify that my "problem" is that copying and pasting the same line of code into ~20 different functions seems like a poor programming style, and I am hoping for a better solution.

Based on what iod and Gregor wrote, the two ways to handle this are:

(1) Require the user to apply the standardizerFunction before running any of the main functions. The functions will the throw an error if the input is of the wrong class.

(2) Since our functions will be checking the input to make sure it is of the right class anyway, just fold standardizerFunction into the input checking part using something like:

if(!inherits(x, what="YourClass")) standardizerFunction(x)

In my particular setting, since most of my users are uncomfortable with R, asking them to pre-apply the standardizerFunction is not the best choice, so I am going with option 2.

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