2017-08-06 39 views
2

假設我有一個使用下面的方法產生的變量x:你會如何適應伽瑪分佈到R中的數據?

x <- rgamma(100,2,11) + rnorm(100,0,.01) #gamma distr + some gaussian noise 

    head(x,20) 
[1] 0.35135058 0.12784251 0.23770365 0.13095612 0.18796901 0.18251968 
[7] 0.20506117 0.25298286 0.11888596 0.07953969 0.09763770 0.28698417 
[13] 0.07647302 0.17489578 0.02594517 0.14016041 0.04102864 0.13677059 
[19] 0.18963015 0.23626828 

我怎麼能適應gamma分佈呢?

+1

見功能'MASS :: fitdistr'。 –

+3

對不起,我剛剛看到你的數據更密切,它的圖。你爲什麼想要適應伽瑪? 'all.equal(seq(0,1,by = 0.01),x)'返回'TRUE'。 –

+0

@RuiBarradas - 謝謝 - 讓我更新這個問題 - 我通過添加少量的高斯噪聲來伽瑪偏差 - 讓我張貼在筆記 – user1172468

回答

2

一個很好的選擇是ML Delignette-Muller等人的fitdistrplus包。例如,使用你的方法生成的數據:

set.seed(2017) 
x <- rgamma(100,2,11) + rnorm(100,0,.01) 
library(fitdistrplus) 
fit.gamma <- fitdist(x, distr = "gamma", method = "mle") 
summary(fit.gamma) 

Fitting of the distribution ' gamma ' by maximum likelihood 
Parameters : 
     estimate Std. Error 
shape 2.185415 0.2885935 
rate 12.850432 1.9066390 
Loglikelihood: 91.41958 AIC: -178.8392 BIC: -173.6288 
Correlation matrix: 
      shape  rate 
shape 1.0000000 0.8900242 
rate 0.8900242 1.0000000 


plot(fit.gamma) 

enter image description here

+1

此解決方案可能存在問題。有'x'的負值。 'sum(x <0)'返回5.當應用於這個向量時,'MASS :: fitdistr'給出一個錯誤:'fitdistr(x,「gamma」)中的錯誤:gamma值必須大於等於0。所以也許包'fitdistrplus'正在做它應該做的所有檢查。 –

+0

@RuiBarradas,謝謝。好點子。上面編輯。該函數不接受負值。 –

1

你可以嘗試可以迅速地Gamma分佈。作爲雙參數分佈可以通過找到樣本均值和方差來恢復它們。在這裏,只要平均值爲正數,您可能會有一些樣本爲負值。

set.seed(31234) 
x <- rgamma(100, 2.0, 11.0) + rnorm(100, 0, .01) #gamma distr + some gaussian noise 
#print(x) 

m <- mean(x) 
v <- var(x) 

print(m) 
print(v) 

scale <- v/m 
shape <- m*m/v 

print(shape) 
print(1.0/scale) 

對於我來說,打印

> print(shape) 
[1] 2.066785 
> print(1.0/scale) 
[1] 11.57765 
> 
+1

true(這種方法被稱爲「矩量法」),但是我希望以這種方式對裂縫進行非常仔細的審查(據稱是Gamma分佈樣本中存在負值)...... –