NonSleeper
NonSleeper

Reputation: 851

How to refer to the function arguments in quotes?

I'm specifying a function to plot graphs like this:

func.plot <- function(z){
  df %>%
    ggplot(aes(z)) + 
    geom_histogram(aes(y =..density..), 
                   binwidth = 0.004,
                   col="red", 
                   fill="green", 
                   alpha=.2) + 
    geom_density(col=2) + 
    labs(title="title", x="z", y="vertical axis")
}

The purpose is to produce histogram plots for a few variables in the data set, hence in this function I also want to use the variable names for the titles of the x axis so as to make the plots differentiated. However, when calling the function with a variable such as func.plot(var) there's an error saying:

Don't know how to automatically pick scale for object of type tbl_ts/tbl_df/tbl/data.frame. Defaulting to continuous.

Error: Aesthetics must be either length 1 or the same as the data (883): x

I've got a few questions:

  1. For this specific function, how to fix it?

  2. More generally, at times I want to write functions that refer to the argument in quotes, such as the x title above. Another simple example will be to read or write data like this:

func.write <- function(x){
  write.csv(x, file="x.csv", row.names=FALSE)
}

This function is also not implemented properly when called out with func.write(df). It will write the data but under the name of "x.csv".

Upvotes: 3

Views: 2898

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

Depending on how you want to pass the input arguments you can use one of the below function.

To pass quoted arguments :

library(ggplot2)
library(rlang)

func.plot_quoted <- function(df, z){
   df %>%
     ggplot(aes(!!sym(z))) + 
     geom_histogram(aes(y =..density..), 
                        binwidth = 0.004,
                        col="red", 
                        fill="green", 
                        alpha=.2) + 
     geom_density(col=2) + 
     labs(title="title", x=z, y="vertical axis")
}

which can be used as

func.plot_quoted(mtcars, "cyl")

and to pass unquoted arguments

func.plot_unquoted <- function(df, z){
    df %>%
      ggplot(aes({{z}})) + 
      geom_histogram(aes(y =..density..), 
                     binwidth = 0.004,
                     col="red", 
                     fill="green", 
                     alpha=.2) + 
      geom_density(col=2) + 
      labs(title="title", x={{z}}, y="vertical axis")
} 

which can be used as

func.plot_unquoted(mtcars, cyl)

enter image description here

Upvotes: 6

Related Questions