Search code examples
rchi-squaredgoodness-of-fit

How do I retrieve the results of a chi-squared goodness-of-fit test using goodfit?


I'm trying to write a piece of software in R that finds the most fitting distribution family to a set of data by performing the chi-squared test on the data (with regards to said family) and finding the best chi-squared value.

However, when using the goodfit function, seemingly the only way to retrieve the chi-squared statistic is by running the function and using the summary(gf) command. This only results in a human-readable output, and I need something that I can draw in the form of gf$chisqvalue so that I can compare it to the results of the other tests I'm running. Is there any way to retrieve this statistic as a variable?


Solution

  • Try the broom package and the command "tidy" like this:

    library(vcd)
    library(broom)
    
    x <- rnbinom(200, size = 3, prob = 0.2)
    res <- goodfit(x, type = "nbinomial", method = "MinChisq")
    summary(res)
    
    dt_res = tidy(summary(res))
    

    This will get the human-readable info and save it in a data.frame. You might prefer to change the column names after (or maybe not). The broom package is great if you want to create a data.frame from a statistical test or model output.