Home > Net >  How do I reference specific column names during package development?
How do I reference specific column names during package development?

Time:12-30

I am developing a package that contains wrappers around ggplot2 functions for dealing with data created by a specific program I often work with. The data always have the same column names, including, for example, "tick." I want to have a function that looks like this.

dynamic_plot <-
  function(
    .data, # A tibble
    y_axis, # The name of the variable to put on the y-axis
    reporter_names = NULL # The name of the variable to map to color
) {


plt <-
  .data |>
  ggplot2::ggplot(
    mapping = ggplot2::aes(
      x = tick,
      y = y_axis,
      color = reporter_names
    )
  )

This would allow the user to create a plot very quickly like this:

dynamic_plot(
  data = my_data,
  y_axis = dependent_variable,
  reporter_names = independent_variable
)

And quickly get a lineplot with one line per each independent variable condition. However, when I try and compile the documentation, I get an error.

 Error in FUN(X[[i]], ...) : object 'dependent_variable' not found.

Adding 'dependent_variable' to globals.R and using utils::globalVariables() hasn't been helping. Any advice?

CodePudding user response:

You can use the "curly curly" method as described here, to be quoted and passed to ggplot.

dynamic_plot <-
  function(.data, # A tibble
           y_axis, # The name of the variable to put on the y-axis
           reporter_names = NULL # The name of the variable to map to color
  ) {
    plt <-
      .data |>
      ggplot2::ggplot(
        mapping = ggplot2::aes(
          x = tick,
          y = {{ y_axis }},
          color = {{ reporter_names }}
        )
      )  
      ggplot2::geom_line()
    plt
  }

my_data <- tibble::tibble(
  tick = rep(1:10, 3),
  juiciness = 1:30 * runif(30),
  juice = rep(c("a", "b", "c"), each = 10)
)



dynamic_plot(
  .data = my_data,
  y_axis = juiciness,
  reporter_names = juice
)

Created on 2021-12-29 by the reprex package (v2.0.1)

  • Related