0
$\begingroup$

Dear StackExchange community,

I am trying to write a function to automate some normality-checks. Here is my try (automates Shapiro-Wilk test, histogram and Q-Q plot creation ):

testfunction <- function (a,b, na.rm = TRUE) {
a <- rlang::sym(quo_name(enquo(a)))
b <- rlang::sym(quo_name(enquo(b)))
histogram <- ggplot(dat, aes(x=!!a, fill=!!b, color=!!b)) +
    geom_histogram(position="identity", alpha=0.5) 
print(histogram)
shapiro.normality <- shapiro.test(a)
print(shapiro.normality)
qqplot <- qqline(a)
print(qqplot)
}

When I try to run the function by placing some arguments ("var4" is a continuous variable and "group" is a dichotomous variable of the "dat" dataframe) I get the following error:

testfunction(a="var4",b="group")

> Error in shapiro.test(a) : is.numeric(x) is not TRUE

I just get the histogram, but no Q-Q plot or results of the Shapiro-Wilk test. Do you have any suggestions for a solution?

Thank you very much.

$\endgroup$
0
$\begingroup$

There are several issues with your code:

  • it is not reproducible because you don't provide dat
  • you don't load all the required libraries
  • you don't create a plot on top of which qqline can draw a line
  • basic plotting and ggplot2 don't mix well
  • and, of course, your core problem: you don't provide the data frame from which a is to select the variable

Here is what I suppose might be the solution you're looking for:

testfunction <- function (a, b, na.rm = TRUE) {
  a <- rlang::sym(dplyr::quo_name(dplyr::enquo(a)))
  b <- rlang::sym(dplyr::quo_name(dplyr::enquo(b)))
  histogram <-
    ggplot2::ggplot(dat, ggplot2::aes(x=!!a, fill=!!b, color=!!b)) +
      ggplot2::geom_histogram(position="identity", alpha=0.5)
  print(histogram)
  shapiro.normality <- shapiro.test(dat[[a]])
  print(shapiro.normality)
  qqplot <- ggplot2::ggplot(dat, ggplot2::aes(sample=!!a, fill=!!b, color=!!b)) +
    ggplot2::stat_qq() +
    ggplot2::geom_abline(ggplot2::aes(slope = 1, intercept = 0), linetype = 2)
  print(qqplot)
}

Calling it by

dat <- data.frame(group=rep(c("A", "B"), each=50), var4=rnorm(100))
testfunction(a="var4", b="group")

produces

    Shapiro-Wilk normality test

data:  dat[[a]]
W = 0.98366, p-value = 0.2534

histogram

qqplot

(of course, you could also load tidyverse to avoid specifying the libraries explicitly)

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.