r - How to plot a function that calculates the PDF? -


so pdf function calculates:

fx = 0.3 if (0<=x<1) 0.1 if (1<=x<2) 0.25 if (2<=x<3) 0.15 if (3<=x<4) 0.2 if (4<=x<5) 0 otherwise


, coding it:

    fx = function(x)     {      if ((0<=x) & (x<1)) 0.3     else if ((1<=x) & (x<2)) 0.1     else if ((2<=x) & (x<3)) 0.25     else if ((3<=x) & (x<4)) 0.15     else if ((4<=x) & (x<5)) 0.2     else 0     } 


how go plotting y=fx?
i've tried:

    x <- runif(n,0,5)     y <- fx(x)     plot(x, y, type='1', xlim=c(0,5), ylim=c(0,5)) 

but error 'x' , 'y' have differing lengths?

your problems comes down fact function isn't vectorized (it doesn't deal vector well).

if use accepted solution previous question exactly same problem won't have issues

eg

# solution work , vectorized fx <- function(x) c(0, 0.3,0.1,0.25,0.15,0.20, 0)[findinterval(x, c(-inf, 0:5, inf))]    x <- runif(n,0,5)  plot(x, fx(x)) 

if want plot step function (which pdf is), can use stepfun

eg

fx <- stepfun(x = 0:5, y = c(0,0.3,0.1,0.25,0.15,0.20,0)) plot(fx, ylim = c(0,0.4),xlim = c(0,5), main = 'f(x)') 

enter image description here

if don't want points added

plot(fx, ylim = c(0,0.4),xlim = c(0,5), main = 'f(x)', do.points=false) 

if want vectorize step function, use vectorize

 vfx <- vectorize(fx) 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -