In R, getting the following error: “attempt to replicate an object of type ‘closure'”

There are a few small issues. ifelse is a vectorized function, but you just need a simple if. In fact, you don’t really need an else — you could just throw an error immediately if the data set does not exist. Note that your error message is not using the name of the object, so it will create its own error.

You are passing a and b instead of "a" and "b". Instead of the ds$x syntax, you should use the ds[[x]] syntax when you are programming (fortunes::fortune(312)). If that’s the way you want to call the function, then you’ll have to deparse those arguments as well. Finally, I think you want deparse(substitute()) instead of deparse(quote())

scatter_plot <- function(ds) {
  ds.name <- deparse(substitute(ds))
  if (!exists(ds.name))
    stop(sprintf("The dataset %s does not exist.", ds.name))
  function(x, y) {
    x <- deparse(substitute(x))
    y <- deparse(substitute(y))
    plot(ds[[x]], ds[[y]])
  }
}
scatter_plot(mydata)(a, b)

Leave a Comment