xtabs counts with NA and na.action = na.pass in R
Asked Answered
C

1

1

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?

Catrinacatriona answered 21/5, 2019 at 12:7 Comment(1)
Follow-up question (bug in documentation): https://mcmap.net/q/1977620/-inconsistency-of-na-action-between-xtabs-and-aggregate-in-rCatrinacatriona
D
1

Change na.action=na.pass to na.action=NULL.

xtabs(formula = cbind(B, C) ~ A,
      data = x,
      addNA = TRUE,
      na.action = NULL)

A      B C
  Y    1 2
  Z    0 0
  <NA> 1 0

Deathblow answered 21/5, 2019 at 15:43 Comment(1)
Thank you verry much! I tried everything except that!Catrinacatriona

© 2022 - 2024 — McMap. All rights reserved.