Including NA Values in structable()

133 Views Asked by At

I would like to make a contingency table using the vcd package structable function. Two of my selected columns (consent_a and consent_b) has NA values as well as factor (Yes, No) values, because each case can be consented for procedure a OR procedure b, but not both. For instance if a case is consented for procedure a, they are not asked for procedure b (and thus consent_b would be NA). In the contingency table, I want to include all cases where factor is yes, no, and NA.

library(vcd)

mydata <- data.frame(
  report_year = c(2013, 2013, 2013, 2013, 2013, 2014, 2014, 2014, 2014, 2014),
  report_week = c(1, 1, 1,  1, 1, 2, 2, 2, 2, 2),
  consenta = c("Yes", "Yes", NA, "Yes", "No", "Yes", "Yes", NA, "Yes", "No"),
  consentb = c(NA, NA, NA, NA, "Yes", NA, NA, "Yes", NA, "No"))

epicurve <- as.data.frame(structable(proj11[, c("report_epiweek", "report_year", "consent_a", "consent_b")]))
1

There are 1 best solutions below

0
lotus On

I'm not familiar with the vcd package but as far as I can see there's no inbuilt means for retaining NA values when working with contingency tables. However, you can achieve the same flattened table while keeping NAs with the base table() function.

as.data.frame(with(mydata, table(report_week, report_year, consent_a, consent_b, useNA = "ifany")))

If the result of this isn't suitable for your next steps then you could just replace the NAs in your dataset with a symbolic value and continue to use the vcd package.