Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

closures

r

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

Why does this not work? I get

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

Didn't quite understand the answer to the other similar posts since I'm quite new to this. How do I fix it?

like image 470
JoeDoe Avatar asked Oct 08 '15 18:10

JoeDoe


1 Answers

The ecdf function is really a functional, i.e. its value is another function. In R the things we call "functions" are really "closures". They have a body that is the code block that is easy to see by typing the function name. However they also have an environment that carries around the local values of variables that are defined at the time of the closure's creation.

If you don't want to provide new values to W that is different than the original values used for its creation, then you need to extract the values from the environment holding the values that existed (and were created) at the time of the call to ecdf with .... wait for it .... the environment-function. The ls function will return the names of the contents of that environment:

 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"

To deliver the sum of the original x-values:

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

It is possible to display the entire contents of an environment by coercing to a data-object with 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
like image 134
IRTFM Avatar answered Oct 20 '22 09:10

IRTFM