r - uniqueN 在 j 中的条件下返回错误结果

标签 r data.table

给定这样的数据集:

 test =data.table(
  id = c("a", "b", "c", "d", "e", "e", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t"),
  int=c(NA, NA, 0, 0, 1, 2, 3, 1, 2, 2, 3, 4, NA, 5, NA, 6, 7, NA, 8, NA, 8, 10))

我想计算 int 具有特定值的唯一 ID 的数量:

test[, .(three=uniqueN(id[int==3]), zero=uniqueN(id[int==0]), missing= uniqueN(id[is.na(int)]))]

结果

   three zero missing
1:     3    3       6

显然是错误的:只有 2 个 id 的 int 为 0 或 3。正确的结果应该如下所示:

   three zero missing
1:     2    2       6

这种方法有什么问题吗? 非常感谢。

最佳答案

int中有NA元素,需要注意,即==NA返回NA。使用 %in% 或使用 &!is.na 创建第二个条件,即该值不是 NA 以便 NA 元素返回 FALSE 而不是 NA

test[, .(three = uniqueN(id[int == 3 & !is.na(int)]), 
         zero=uniqueN(id[int %in% 0]))]
#    three zero
#1:     2    2

或者另一种选择是在 uniqueN 中使用 na.rm,默认情况下为 FALSE,因此,它会计算 >NA 作为另一个唯一值

test[, .(three=uniqueN(id[int==3], na.rm = TRUE), 
       zero=uniqueN(id[int==0], na.rm = TRUE),
       missing= uniqueN(id[is.na(int)]))]
#   three zero missing
#1:     2    2       6

或者另一种方法是首先使用 na.omitcomplete.cases 处理 NA,然后使用 OP 的代码

na.omit(test)[, .(three = uniqueN(id[int == 3]),
      zero = uniqueN(id[int == 0]))]
#    three zero
#1:     2    2

通过执行 == 而不考虑 NA,它会返回 NA 而不是 FALSE 并且这个子集化时也会返回NA

c(NA, 3) == 3
#[1]   NA TRUE

c(5, 4)[c(NA, 3) == 3]
#[1] NA  4

c(NA, 3) == 3 & !is.na(c(NA, 3))
#[1] FALSE  TRUE

或者使用%in%

c(NA, 3) %in% 3
#[1] FALSE  TRUE

关于r - uniqueN 在 j 中的条件下返回错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66040616/

相关文章:

r - 与 sf 包一起使用时 data.table 的行为不正确

r - 在 R 中有效地填充平均值旁边的值

r - 将小数格式化为整数时,noUiSliderInput() 中的奇怪行为,例如5.00 至 5

r - 在 R : recursive function that operates on its own previous result 中应用

r - 函数参数作为R函数中的参数

regex - 测试两列字符串以在 R 中逐行匹配

r - 将 table() 函数实现为用户定义的函数

R 中空白条目的行

r - 使用相似数据帧的内容来提高更新大数据帧内容的性能

r - 对于这些查找表样式查询,为什么 data.table 比基本 R 慢?