Reputation: 577
I'm getting this error message even though I don't have any NA's, negative counts, etc.
I'm trying to do a post-hoc chi-square test on this data:
df <- structure(list(Zone = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("Crocodile",
"Rankin", "West", "Whipray"), class = "factor"), Year = structure(c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("2016",
"2017", "2018", "2019"), class = "factor"), empty_num_sum = c(0L,
8L, 2L, 0L, 3L, 17L, 8L, 19L, 7L, 31L, 17L, 17L, 4L, 4L, 0L,
3L)), row.names = c(NA, -16L), groups = structure(list(Zone = structure(1:4, .Label = c("Crocodile",
"Rankin", "West", "Whipray"), class = "factor"), .rows = structure(list(
1:4, 5:8, 9:12, 13:16), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
But it keeps giving me this error...
chisq.posthoc.test(df, method = "bonferroni")
Error in chisq.test(x, ...) :
all entries of 'x' must be nonnegative and finite
Upvotes: 1
Views: 705
Reputation: 173928
You need to pass your counts as a matrix / contingency table. You can easily convert your data frame to this format using the xtabs
function:
xtab <- xtabs(empty_num_sum ~ Zone + Year, data = df)
xtab
#> Year
#> Zone 2016 2017 2018 2019
#> Crocodile 0 8 2 0
#> Rankin 3 17 8 19
#> West 7 31 17 17
#> Whipray 4 4 0 3
So now you can do:
library(chisq.posthoc.test)
chisq.posthoc.test(xtab)
#> Warning in chisq.test(x, ...): Chi-squared approximation may be incorrect
#> Dimension Value 2016 2017 2018 2019
#> 1 Crocodile Residuals -1.0938835 2.46306043 0.0594116 -2.03921942
#> 2 Crocodile p values 1.0000000 0.22041100 1.0000000 0.66285000
#> 3 Rankin Residuals -1.0141479 -1.13659482 -0.4827683 2.35822986
#> 4 Rankin p values 1.0000000 1.00000000 1.0000000 0.29379700
#> 5 West Residuals -0.1127333 0.04881493 1.3347770 -1.15317201
#> 6 West p values 1.0000000 1.00000000 1.0000000 1.00000000
#> 7 Whipray Residuals 3.0363341 -0.45336940 -1.6889164 -0.04504248
#> 8 Whipray p values 0.0383160 1.00000000 1.0000000 1.00000000
Created on 2022-02-07 by the reprex package (v2.0.1)
Upvotes: 1