xtabs 用 NA 和 na.action = na.pass 在 R 中计数 [英] xtabs counts with NA and na.action = na.pass in R
问题描述
我有以下 data.frame
:
x <- data.frame(A = c("Y", "Y", "Z", NA),
B = c(NA, TRUE, FALSE, TRUE),
C = c(TRUE, TRUE, NA, FALSE))
我需要计算下表:
A B C
Y 1 2
Z 0 0
<NA> 1 0
但是,即使使用 na.action = na.pass
,我也无法使用 xtabs
实现此结果:
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
来自?xtabs
:
na.action
一个函数,它指示当数据包含 NA.如果未指定,并且 addNA 为真,则设置为na.pass.当它是 na.pass 并且公式有左侧时(与counts),使用 sum(*, na.rm = TRUE) 代替 sum(*) 来表示计数.
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.
添加NA
逻辑指示 NA 是否应该获得单独的级别并被计数,使用 addNA(*, ifany=TRUE) 并设置默认值无行动.
addNA
logical indicating if NAs should get a separate level
and be counted, using addNA(*, ifany=TRUE) and setting the default for
na.action.
作为一种解决方法,我可以将 NA
替换为 FALSE
:
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
或者我可以使用聚合:
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
但是如何用 xtabs
得到这个表而不用 FALSE
替换 NA
?
But how get this table with xtabs
without replacing NA
by FALSE
?
推荐答案
将 na.action=na.pass
更改为 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
这篇关于xtabs 用 NA 和 na.action = na.pass 在 R 中计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!