Re: [R] how to plot an user-defined function

From: jim holtman <jholtman_at_gmail.com>
Date: Tue, 5 Feb 2008 21:52:09 -0500

Your function 'll' only returns a single value when passed a vector:

> x <- seq(0,2,.1)
> ll(x)

[1] -7.571559

'plot' expects to pass a vector to the function and have it return a vector of the same length; e.g.,

> sin(x)

 [1] 0.00000000 0.09983342 0.19866933 0.29552021 0.38941834 0.47942554 0.56464247 0.64421769 0.71735609
[10] 0.78332691 0.84147098 0.89120736 0.93203909 0.96355819 0.98544973 0.99749499 0.99957360 0.99166481
[19] 0.97384763 0.94630009 0.90929743
>

So you either have to rewrite your function, or have a loop that will evaluate the function at each individual point and then plot it.

On Feb 5, 2008 7:06 PM, John Smith <zmring_at_gmail.com> wrote:
> Dear R-users,
>
> Suppose I have defined a likelihood function as ll(tau), how can I plot this
> likelihood function by calling it by plot?
>
> I want to do it like this:
>
> ll <- function(tau)
> {
> w <- 1 / (s^2 + tau^2)
> mu <- sum(theta * w) / sum(w)
> -1/2*sum((theta-mu)^2*w -log(w))
> }
> plot(ll, 0, 2)
>
>
>
> But have the following error:
> Error in xy.coords(x, y, xlabel, ylabel, log) :
> 'x' and 'y' lengths differ
> In addition: Warning messages:
> 1: In s^2 + tau^2 :
> longer object length is not a multiple of shorter object length
> 2: In theta * w :
> longer object length is not a multiple of shorter object length
> 3: In (theta - mu)^2 * w :
> longer object length is not a multiple of shorter object length
>
>
> Thanks
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Wed 06 Feb 2008 - 02:55:06 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 06 Feb 2008 - 04:30:11 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive