Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I am having the following code and when I try to call f() then this is giving me the error.

The code is:

XI am having the following code and when I try to call f() then this is giving me the error.

The code is:

library(tidyverse)

piechart <- function(data, mapping) {

  ggplot(data, mapping) +

    geom_bar(width = 1) + 

    coord_polar(theta = "y") + 

    xlab(NULL) + 

    ylab(NULL)

}

piechart3 <- function(data, var, ...) {

  piechart(data, aes_(~factor(1), fill = substitute(var)))

}

f <- function() {

  levs <- c("2seater", "compact", "midsize", "minivan", "pickup", 

            "subcompact", "suv")

  piechart3(mpg, factor(class, levels = levs))

}

f()

And the error is:

"Error in factor(class, levels = levs) : object 'levs' not found".

And the error is:

"Error in factor(class, levels = levs) : object 'levs' not found".

1 Answer

0 votes
by (108k points)

What you have to do is to evaluate the unquoted variable as column of the data-frame and in R programming you can do that with the help of {{}}.

library(ggplot2)

library(rlang)

piechart <- function(data, mapping) {

   ggplot(data, mapping) +a

     geom_bar(width = 1) + 

     coord_polar(theta = "y") + 

     xlab(NULL) + 

     ylab(NULL)

}

piechart3 <- function(data, var, ...) {

   piechart(data, aes(factor(1), fill = {{var}}))

}

f <- function() {

  levs <- c("2seater", "compact", "midsize", "minivan", "pickup", 

        "subcompact", "suv")

  mpg$class <- factor(mpg$class, levels = legs)

  piechart3(mpg, class)

}

f()

 The plot will look like this:enter image description here

Browse Categories

...