[R] How to use curve() function without using x as the variable name inside expression?

peter dalgaard pdalgd at gmail.com
Sat Jan 31 09:58:36 CET 2015


> On 31 Jan 2015, at 09:39 , Rolf Turner <r.turner at auckland.ac.nz> wrote:
> 
> On 31/01/15 21:10, C W wrote:
>> Hi Bill,
>> 
>> One quick question.  What if I wanted to use curve() for a uniform
>> distribution?
>> 
>> Say, unif(0.5, 1.3), 0 elsewhere.
>> 
>> My R code:
>> func <- function(min, max){
>>   1 / (max - min)
>> }
>> 
>> curve(func(min = 0.5, max = 1.3), from = 0, to = 2)
>> 
>> curve() wants an expression, but I have a constant.   And I want zero
>> everywhere else.
> 
> Well if that's what you want, then say so!!!
> 
> func <- function(x,min,max) {
>   ifelse(x < min | x > max, 0, 1/(max - min))
> }
> 

Oy! help(Uniform) called. I wants its density function back...

> curve(func(u,0.5,1.3),0,2,xname="u")
> 
> Or, better (?) curve(func(u,0.5,1.3),0,2,xname="u",type="s")
> 
> which avoids the slight slope in the "vertical" lines.

It might put the verticals in the wrong place though. I usually just increase the "n" parameter:

curve(dunif(u,.5, 1.3), from=0, to=2, n=5001, xname="u") 


-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list