2016-12-25 126 views
1

我有以下功能:如何從PDF繪製CDF functon R中

fx <- function(x) { 
    if(x >= 0 && x < 3) { 
    res <- 0.2; 
    } else if(x >=3 && x < 5) { 
    res <- 0.05; 
    } else if(x >= 5 && x < 6) { 
    res <- 0.15; 
    } else if(x >= 7 && x < 10) { 
    res <- 0.05; 
    } else { 
    res <- 0; 
    } 

    return(res); 
} 

我如何可以繪製它是在間隔[0,10]CDF功能?

回答

2

要將位精度添加到@馬丁施梅爾策的回答。甲累積性分佈函數(CDF)

在x處評估的概率是X將小於 或等於值x

所以從概率密度函數得到CDF (PDF),你需要在PDF整合:

fx <- Vectorize(fx) 
dx <- 0.01 
x <- seq(0, 10, by = dx) 
plot(x, cumsum(fx(x) * dx), type = "l", ylab = "cummulative probability", main = "My CDF") 

enter image description here

+0

對不起,我錯了。對我來說太遲了。時間去睡覺:) –

+0

@MartinSchmelzer當然。別擔心。 – Psidom

+0

它實際上不是一個單一的值,因爲我們矢量化了'fx',它需要一個矢量'x'並返回另一個矢量。運行'Vectorize(fx)(x)',其中'x < - seq(0,10,by = 0.01)' – Psidom

5

嘗試

fx <- Vectorize(fx) 
grid <- 0:10 
p <- fx(grid) 
cdf <- cumsum(p) 

plot(grid, cdf, type = 'p', ylim = c(0, 1), col = 'steelblue', 
    xlab = 'x', ylab = expression(F(x)), pch = 19, las = 1) 
segments(x0 = grid, x1 = grid + 1, y0 = cdf) 
segments(x0 = grid + 1, y0 = c(cdf[-1], 1), y1 = cdf, lty = 2) 

enter image description here

0

在以前的答案只是添加和使用ggplot

# cdf 
Fx <- function(x, dx) { 
    cumsum(fx(x)*dx) 
} 

fx <- Vectorize(fx) 
dx <- 0.01 
x <- seq(0, 10, dx) 
df <- rbind(data.frame(x, value=fx(x), func='pdf'), 
      data.frame(x, value=Fx(x, dx), func='cdf')) 
library(ggplot2) 
ggplot(df, aes(x, value, col=func)) + 
    geom_point() + geom_line() + ylim(0, 1) 

enter image description here