在R中,得到以下错误:“试图复制类型为'closure'的对象” [英] In R, getting the following error: "attempt to replicate an object of type 'closure'"

查看:4993
本文介绍了在R中,得到以下错误:“试图复制类型为'closure'的对象”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个R函数,它接受一个数据集,并输出plot()函数与在其环境中读取的数据集。这意味着你不必再使用attach()了,这是良好的做法。这是我的例子:

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() anymore, which is good practice. Here's my example:

mydata <- data.frame(a = rnorm(100), b = rnorm(100,0,.2))
plot(mydata$a, mydata$b) # works just fine

scatter_plot <- function(ds) { # function I'm trying to create
    ifelse(exists(deparse(quote(ds))),
        function(x,y) plot(ds$x, ds$y),
            sprintf("The dataset %s does not exist.", ds))
    }

scatter_plot(mydata)(a, b) # not working

这是我得到的错误:

Error in rep(yes, length.out = length(ans)) : 
  attempt to replicate an object of type 'closure'

我试过几个其他版本,但他们都给我相同的错误。我做错了什么?

I tried several other versions, but they all give me the same error. What am I doing wrong?

编辑:我意识到代码不太实用。我的目标是更好地理解函数式编程。我在SAS中写了一个类似的宏,我只是试图在R中写它的对应,但我失败了。我只是选择这个例子。我认为这是一个很简单的例子,但它不工作。

I realize the code is not too practical. My goal is to understand functional programming better. I wrote a similar macro in SAS, and I was just trying to write its counterpart in R, but I'm failing. I just picked this as an example. I think it's a pretty simple example and yet it's not working.

推荐答案

有一些小问题。 ifelse 是一个矢量化函数,但你只需要一个简单的 if 。事实上,你不需要一个 else - 如果数据集不存在,你可以立即抛出一个错误。请注意,您的错误消息未使用对象的名称,因此会创建自己的错误。

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.

您正在传递 a b 而不是ab。而不是 ds $ x 语法,你应该使用 ds [[x]] fortunes :: fortune(312))。如果这是你想调用的函数的方式,那么你将不得不deparse这些参数。最后,我想你想要 deparse(substitute())而不是 deparse(quote())

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)

这篇关于在R中,得到以下错误:“试图复制类型为'closure'的对象”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆