【问题标题】:Looping over every year and apply a function每年循环并应用一个函数
【发布时间】:2014-07-18 13:11:36
【问题描述】:

我有一个数据框,其中包含观察到的变量和运行数千行的日期戳 [Var1, DD, MM, YYYY]。我需要为每年的观察变量拟合分布[指数或伽马],并获得每年的相关参数。

在 Matlab 中,它只是

 j=1
 k=1

 for i=1:(no_of_rows-1)

    if  year(i+1) = year(i)
        temp_data_year(j) = Var1(i)
        j=j+1

    else  [a,b]= gamfit(temp)
         param(:,:,k) = [a,b]
         k=k+1
   endif

 end   

所以我会在变量 param 的数据中获取每年的参数。

那么 R 中有什么东西可以做到这一点吗?

谢谢,

【问题讨论】:

  • 查看?by,将您的年份变量放入INDICES 参数中,并将您的分布拟合器(?MASS::fitdistr)放入FUN 参数中。祝你好运。

标签: r matlab for-loop gamma-distribution


【解决方案1】:

像这样。

# creates a sample dataset - you have this already
set.seed(1)             # for reproducible example
df <- data.frame(var1=c(rgamma(365,2,4),rgamma(365,3,5),rgamma(365,1,8)),
                 YYYY=rep(2012:2014,each=365))

# you start here...
library(fitdistrplus)   # for fitdist(...)
aggregate(var1~YYYY,df,function(X)fitdist(X,distr="gamma")$estimate)
#   YYYY var1.shape var1.rate
# 1 2012   1.891706  3.873906
# 2 2013   2.812962  4.778191
# 3 2014   1.031067  7.826776

阅读fitdistrplus 包中fitdist(...) 的文档。有几种拟合算法可用。

【讨论】:

  • 成功了。但是我收到很少的警告消息“在 densfun(x,...):NaNs 中产生”。我应该担心吗?
  • 不一定。可能是起始参数估计(由fitdist(...) 选择)离 MLE 太远了。您需要根据数据的直方图绘制分布函数,以验证拟合是否良好。此外,您可以使用 `start=...' 参数指定起始估计值。阅读文档。
猜你喜欢
  • 1970-01-01
  • 2019-11-10
  • 2011-10-24
  • 2018-12-27
  • 1970-01-01
  • 2016-12-21
  • 2013-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多