[R] how to plot an user-defined function
Duncan Murdoch
murdoch at stats.uwo.ca
Wed Feb 6 04:45:41 CET 2008
jim holtman wrote:
> 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.
>
Or use Vectorize, e.g.
plot(Vectorize(ll), 0, 2)
Duncan Murdoch
> 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.
>>
>>
>
>
>
>
More information about the R-help
mailing list