Mat*_*ete 0 plot r function probability
所以这是我的函数计算的PDF:
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
这是我的编码:
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
}
Run Code Online (Sandbox Code Playgroud)
现在我将如何绘制y = fx?
我试过了:
x <- runif(n,0,5)
y <- fx(x)
plot(x, y, type='1', xlim=c(0,5), ylim=c(0,5))
Run Code Online (Sandbox Code Playgroud)
但是我得到一个'x'和'y'有不同长度的错误?
你的问题归结为你的函数没有正确矢量化(它没有很好地处理矢量).
如果您使用 上一个问题中接受的关于完全相同问题的解决方案,那么您将不会遇到任何问题
例如
# 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))
Run Code Online (Sandbox Code Playgroud)
如果你想绘制一个阶梯函数(这是这个pdf是什么),你可以使用 stepfun
例如
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)')
Run Code Online (Sandbox Code Playgroud)
如果您不想要添加点数
plot(fx, ylim = c(0,0.4),xlim = c(0,5), main = 'f(x)', do.points=FALSE)
Run Code Online (Sandbox Code Playgroud)
如果要对步进函数进行矢量化,请使用 Vectorize
vfx <- Vectorize(fx)
Run Code Online (Sandbox Code Playgroud)