Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)

enter image description here


Data

OBX <- rnorm(100)
DNB <- rnorm(100)
DNC <- rnorm(100)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading