# 如何绘制一个计算PDF的函数？How to plot a function that calculates the PDF?

fx = 0.3，如果（0 <= x <1）0.1，如果（1 <= x <2）0.25，如果（2 <= x <3），0.15，如果，（3 <= x <4），如果，（4 <= x < 5）否则为0

``````    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
}
``````

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

## 2 个回复2

### ===============>>#1 票数：6 已采纳

``````# a solution that will work and be properly 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))
``````

``````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)')
``````

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

`````` vfx <- Vectorize(fx)
``````

### ===============>>#2 票数：1

``````fx <- function(x) {
ifelse((0<=x) & (x<1), 0.3,
ifelse((1<=x) & (x<2), 0.1,
ifelse((2<=x) & (x<3), 0.25,
ifelse((3<=x) & (x<4), 0.15,
ifelse((4<=x) & (x<5), 0.2,
0)))))
}

x <- seq(0, 6, length.out=n)
plot(x, fx(x))
``````