I have the following data.frame
:
x <- data.frame(A = c("Y", "Y", "Z", NA),
B = c(NA, TRUE, FALSE, TRUE),
C = c(TRUE, TRUE, NA, FALSE))
I need to compute the following table:
A B C
Y 1 2
Z 0 0
<NA> 1 0
However I am unable to achieve this result with xtabs
, even with na.action = na.pass
:
xtabs(formula = cbind(B, C) ~ A,
data = x,
addNA = TRUE,
na.action = na.pass)
A B C
Y 2
Z 0
<NA> 1 0
From ?xtabs
:
na.action
a function which indicates what should happen when the data contain NAs. If unspecified, and addNA is true, this is set to na.pass. When it is na.pass and formula has a left hand side (with counts), sum(*, na.rm = TRUE) is used instead of sum(*) for the counts.addNA
logical indicating if NAs should get a separate level and be counted, using addNA(*, ifany=TRUE) and setting the default for na.action.
As a workaround, I can replace the NA
by FALSE
:
x[is.na(x$B), "B"] <- FALSE
x[is.na(x$C), "C"] <- FALSE
xtabs(formula = cbind(B, C) ~ A,
data = x,
addNA = TRUE)
A B C
Y 1 2
Z 0 0
<NA> 1 0
Or I can use aggregate:
aggregate(formula = cbind(B, C) ~ addNA(A),
data = x,
FUN = sum,
na.rm = TRUE,
na.action = na.pass)
addNA(A) B C
1 Y 1 2
2 Z 0 0
3 <NA> 1 0
But how get this table with xtabs
without replacing NA
by FALSE
?