为什么我收到错误 "invalid type closure"?

Why am I getting the error "invalid type closure"?

W <- ecdf(c(1,2,3))
W
O <- sum(W)
W

为什么这不起作用?我得到

Error in sum(W) : invalid 'type' (closure) of argument

不太理解其他类似帖子的答案,因为我对此很陌生。我该如何解决?

ecdf函数实际上是一个函数,即它的值是另一个函数。在 R 中,我们称为 "functions" 的东西实际上是 "closures"。它们的主体是代码块,通过键入函数名称很容易看到。然而,它们也有一个 environment,它携带在创建闭包时定义的变量的局部值。

如果您不想向 W 提供不同于用于创建它的原始值的新值,那么您需要从环境中提取值,该值保存在调用 ecdf 的时间……等等……environment 函数。 ls 函数将 return 该环境内容的名称:

 str(W)
#--------
function (v)  
 - attr(*, "class")= chr [1:3] "ecdf" "stepfun" "function"
 - attr(*, "call")= language ecdf(1:11)
#---------------
 # Just asking to see that environment is less than satisfying
  environment(W)
 #<environment: 0x3cd392588>
 # using `ls` is more informative
 ls( environment(W) )
#[1] "f"      "method" "nobs"   "x"      "y"      "yleft"  "yright"

要提供原始 x 值的总和:

> sum( environment(W)$x )
[1] 6

可以通过使用 as.list:

强制转换为数据对象来显示环境的全部内容
> as.list(environment(W))
$nobs
[1] 3

$x
[1] 1 3 5

$y
[1] 0.3333333 0.6666667 1.0000000

$method
[1] 2

$yleft
[1] 0

$yright
[1] 1

$f
[1] 0