Why my fitting distribution in R is throwing out errors?

130 views Asked by At

Here is a sample code where i am trying to fit multiple distribution. Can someone please look into the error and run the code to its entirety? Thanks

# Step 1: Load required libraries
library(ismev)
library(tidyverse)
library(fitdistrplus)

# Step 2: Read and preprocess the streamflow data
streamflow <- data.frame(date = seq(as.Date("1980-01-01"), 
                            to = as.Date("2020-12-31"), 
                            by = "day"), 
                            value = runif(14976,1,500))

# Step 3: Calculate annual maximum flows
annual_max <- aggregate(streamflow$value, by = list(year = format(streamflow$date, "%Y")), FUN = max)

# Step 4: Fit multiple probability distributions to the annual maximum flows
distributions <- c("norm", "logis", "gev")  # Specify the distributions to be fitted
fit_results <- fitdist(annual_max$x, distributions)

# Step 5: Calculate return periods and associated flow values for each distribution
return_periods <- c(2, 5, 10, 25, 50, 100)  # Specify desired return periods in years

# Loop through each distribution and calculate return flows
results <- data.frame(Return_Period = return_periods)
for (i in 1:length(distributions)) {
  return_flows <- qfunc(return_periods, distname = distributions[i], distr = fit_results[[i]])
  results[, paste(distributions[i], "Flow_Value", sep = "_")] <- return_flows
}

Error point at fit_results it throws the following error

fit_results <- fitdist(annual_max$x, distributions)
Error in exists(ddistname, mode = "function") : 
  first argument has length > 1 
1

There are 1 answers

2
jay.sf On

1., fitdistrplus::fitdist isn't vectorized, you need lapply, 2., There does not appear to be a `"gev" distribution available. I have not looked at the rest.

lapply(distributions, \(d) {
  tryCatch(fitdistrplus::fitdist(annual_max$x, d), error=\(e) NA)
})
# [[1]]
# Fitting of the distribution ' norm ' by maximum likelihood 
# Parameters:
#        estimate Std. Error
# mean 498.642567  0.2677010
# sd     1.714123  0.1892929
# 
# [[2]]
# Fitting of the distribution ' logis ' by maximum likelihood 
# Parameters:
#             estimate Std. Error
# location 498.9166249  0.1784073
# scale      0.6861103  0.0924656
# 
# [[3]]
# [1] NA