Reputation: 8403
plot( dnorm , col='white')
polygon( dnorm, col='grey' )
returns the above error message, not on plot
, but on polygon
.
body(polygon) %>% grep(pattern='numeric')
finds only one occurrence on line 4, which doesn't seem to have anything to do with this error. So I'm at a loss as to where to look for the source of the problem.
Upvotes: 1
Views: 3595
Reputation: 8403
You need to polygon( dnorm(-3:3) )
or whatever the xlim
limits are. polygon
lacks a method for treating functions (although plot
has one).
Upvotes: 0
Reputation: 52637
plot
has a function method, whereas polygon
does not. From ?plot
:
x: the coordinates of points in the plot. Alternatively, a single plotting structure, function or any R object with a plot method can be provided.
Additionally, from ?plot.function
, the S3 method to plot functions:
## S3 method for class 'function'
plot(x, y = 0, to = 1, from = y, xlim = NULL, ylab = NULL, ...)
This explains why you get a plot with values from 0 to 1 with plot
when you pass dnorm
as an argument.
Note functions like dnorm
are also known as closures. This explains why you get that error with polygon
. Since polygon does not accept functions as an argument, it tries to convert dnorm
, a closure, to a vector, but that isn't a valid conversion.
The error in polygon
is actually happening in the as.double
call within xy.coord
:
> polygon(dnorm)
Error in as.double(y) :
cannot coerce type 'closure' to vector of type 'double'
> traceback()
2: xy.coords(x, y)
1: polygon(dnorm)
Note as.double
doesn't register in the trace stack because it is a primitive. By looking at the source of xy.coords
, you can see where the error is happening. To semi-confirm:
> as.double(dnorm)
Error in as.double(dnorm) :
cannot coerce type 'closure' to vector of type 'double'
dnorm(-3:3)
actually produces a numeric vector, which is why that works with polygon
.
Upvotes: 3
Reputation: 1707
The call to plot will resolve to a variety of default methods for different types of objects. See methods(plot)
for a list in your environment. For dnorm
it is plot.function
, which takes the function as an argument and provides a set of inputs into the function. Incidentally this will also work with rnorm
because plot.function
provides a default argument of n=101
.
A more common alias for plot.function
is curve
.
curve(dnorm, col="grey")
The polygon
has no such analogous method for various types of objects.
Upvotes: 0