R 每年循环并应用一个函数
我有一个数据框,其中包含一个观察到的变量和运行在数千行上的日期戳[Var1,DD,MM,YYYY]。我需要为每年的观测变量拟合分布[指数或伽马],并获得每年的相关参数 在Matlab中,它只是R 每年循环并应用一个函数,r,matlab,for-loop,gamma-distribution,R,Matlab,For Loop,Gamma Distribution,我有一个数据框,其中包含一个观察到的变量和运行在数千行上的日期戳[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)
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中有什么东西可以做到这一点吗
谢谢,像这样
# 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
#创建一个示例数据集-您已经有了它
设定种子(1)#用于可复制的示例
df通过查看,将年份变量放入索引参数中,将分配装配工(?MASS::fitdistr
)放入乐趣参数中。祝你好运,成功了。但我收到的警告信息很少“在邓斯芬(x,…):南斯制作”。我应该担心吗?不一定。可能是起始参数估计值(由fitdist(…)
选择)与MLE的距离太远。您需要根据数据的直方图绘制分布函数,以验证拟合是否良好。此外,您还可以使用“start=…”参数指定起始估计数。阅读文档。