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

后端 未结 1 1784
不思量自难忘°
不思量自难忘° 2020-12-03 21:02

I am trying to write an R function that takes a data set and outputs the plot() function with the data set read in its environment. This means you don\'t have to use attach

相关标签:
1条回答
  • 2020-12-03 21:35

    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)
    
    0 讨论(0)
提交回复
热议问题