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

橙三吉。 提交于 2020-06-28 06:22:32

问题


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?


回答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



来源:https://stackoverflow.com/questions/56237951/xtabs-counts-with-na-and-na-action-na-pass-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!