Is it possible to have multiple variables for a function in R

Advertisements

I am working on a function where I want to test normality of three time series. I have created the following function:

par(mfrow =  c(3,2))
graphicalnormality = function(x){
  plotNormalHistogram(x)
  normstats = c(mean(x), median(x), quantile(x, c(0.1, 0.9)))
  abline(v = normstats, col = 'red', lwd = 2)
  qqnorm(x)
  qqline(x)
}
graphicalnormality(OBX)
graphicalnormality(DNB)
graphicalnormality(DNO)

It is a very simple function and it works how I want it to, but since I am just a little bit picky and because I am unsure how well it works with RMarkdown, I don’t want to have to run the function three times to get the plot for all three of my tests. So my question is, is it possible to get the function to run for all three data sets in one go?

>Solution :

You can modify your function to take any number of vectors like this:

graphicalnormality = function(...) {
  dfs <- lapply(as.list(match.call())[-1], eval)
  for(x in dfs) {
    rcompanion::plotNormalHistogram(x)
    normstats = c(mean(x), median(x), quantile(x, c(0.1, 0.9)))
    abline(v = normstats, col = 'red', lwd = 2)
    qqnorm(x)
    qqline(x)
  }
}

So you can do:

par(mfrow =  c(3,2))
graphicalnormality(OBX, DNB, DNC)


Data

OBX <- rnorm(100)
DNB <- rnorm(100)
DNC <- rnorm(100)

Leave a ReplyCancel reply