1

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")]))
Leonardo
  • 2,439
  • 33
  • 17
  • 31
MC_W
  • 26
  • 3
  • Please provide a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) of your data. It sounds as if you're confusing `NULL` with `NA` or possibly a string with the value "NULL". These are not the same thing. – Ritchie Sacramento May 01 '19 at 22:42
  • Sorry, you are right. I am mixing up NULL and NA. I have provided additional code above to reproduce my data. Thanks. – MC_W May 02 '19 at 14:22

1 Answers1

1

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.

Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56