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

Why isn't my custom errorbar function working in R?

I have tried to make a function to quickly make an error bar based on a grouping factor and a numerical value as defined below:

#### Function ####
quick.error <- function(data,x,y){
  d <- data
  plot.d <- d %>%
    mutate(x = as.factor(x)) %>% 
    group_by(x) %>%
    summarise(
      sd = sd(y, na.rm = TRUE),
      mean = mean(y, na.rm=TRUE)
    ) %>% 
    ggplot(aes(x, 
               mean,
               fill=x)) +
    geom_col(color = "black") +
    geom_errorbar(aes(ymin = mean-sd,
                      ymax = mean+sd),
                  width = 0.2) +
    theme(legend.position = "none")
  return(plot.d)
}

However, when I try to run this with the iris dataset:

#### Test ####
quick.error(data=iris,
            x=Species,
            y=Petal.Length)

This gives me an error:

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

Error in `mutate()`:
! Problem while computing `x = as.factor(x)`.
Caused by error in `is.factor()`:
! object 'Species' not found

Running it explicitly with $ operators gives me a different issue:

#### Test ####
quick.error(data=iris,
            x=iris$Species,
            y=iris$Petal.Length)

As you can see here, it has made all the bars the same, I assume because it did not group the mean like it was supposed to:

enter image description here

How do I fix this problem?

>Solution :

As I indicate in my comment, this is a typical non-standard evaluation problem. Here’s a revised function that I believe gives you what you want.

quick.error <- function(data,x,y){
  d <- data
  plot.d <- d %>%
    mutate({{ x }} := as.factor({{ x }})) %>% 
    group_by({{ x }}) %>%
    summarise(
      sd = sd({{ y }}, na.rm = TRUE),
      mean = mean({{ y }}, na.rm=TRUE)
    ) %>% 
    ggplot(aes({{ x }}, 
               mean,
               fill={{ x }})) +
    geom_col(color = "black") +
    geom_errorbar(aes(ymin = mean-sd,
                      ymax = mean+sd),
                  width = 0.2) +
    theme(legend.position = "none")
  return(plot.d)
}

quick.error(data=iris,
            x=Species,
            y=Petal.Length)

enter image description here

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