1

I am trying to create a function that takes a data frame, an x-axis variable, and a y-axis variable to create a visual. Here's my code:

library(ggplot2)
create_visual <-
  function(data, x_axis, y_axis) {
    ggplot(data = data) + geom_point(mapping = aes(x = x_axis, y = y_axis))
  }

When I run this code:

create_visual(penguins,flipper_length_mm,body_mass_g)

I get this error: 'Error in FUN(X[[i]], ...) : object 'flipper_length_mm' not found'

I have loaded the dataset Palmerpenguins and checked the penguins data table, and it does have flipper_length_mm, yet I am getting this error. Could you please help me figure out where I am making a mistake?

Isaiah
  • 2,091
  • 3
  • 19
  • 28
Archit
  • 13
  • 3
  • 2
    If the length and mass data are in `penguins` and not stand along objects, you need to do `create_visual(penguins, penguins$flipper_length_mm, penguins$body_mass_g)` – jpsmith Oct 19 '22 at 12:18

3 Answers3

0

You need to provide the function attributes as strings, it are not objects you will provide. This would cause the error. However within your function you have to use get on those strings to get it working. Below a small demo including the use in the graph's title and axis legends.

set.seed(123)

penguins <- data.frame(
  flipper_length_mm = sample(120L:300L, 10L),
  body_mass_g = sample(2200L:4500L, 10L)
)

library(ggplot2)

create_visual <- function(data, x_axis, y_axis) {

    ggplot(data = get(data)) +
    geom_point(aes(x = get(x_axis), y = get(y_axis))) +
    labs(title = paste("Relation between", x_axis, "and", y_axis), x = x_axis, y = y_axis)

}

create_visual("penguins", "flipper_length_mm", "body_mass_g")

enter image description here

Merijn van Tilborg
  • 5,452
  • 1
  • 7
  • 22
0

When using aes() ggplot assumes you are giving it the column names you want to plot (so it thinks your column name is "x_axis" without trying to read its value). To use parameters I would use aes_() instead. example:

create_visual <- function(data,x_axis,y_axis){
   x_axis <- as.name(x_axis)
   y_axis <- as.name(y_axis)
   ggplot(data=data) + geom_point(mapping=aes_(x=x_axis,y=y_axis))
}
Jan
  • 157
  • 9
-2

You can use

attach(penguins)

and then run your code!

  • 3
    Using `attach` is generally a bad idea, especially given that the tidyverse developers have a whole subset of their packages (all of the tidyeval protocols) dedicated to *not* doing this – camille Oct 19 '22 at 13:19
  • Whatever, it works! – Antreas Stefopoulos Oct 19 '22 at 13:24
  • Until you need to do it again, which is the purpose of a function. If you're going to recommend an anti-pattern, at least including the downsides of it and the steps necessary to undo the anti-pattern (calling `detach` after each time you call this function) would be helpful. Otherwise you're just introducing different bugs a couple lines later – camille Oct 19 '22 at 13:39