gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:09:43 24 4
gpt4 key购买 nike

给定这样的数据集:

 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
这种方法有什么问题?
多谢。

最佳答案

NA int 中的元素,需要注意,即 ==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

或者另一种选择是利用 na.rmuniqueN默认情况下是 FALSE ,因此,它计算 NA作为另一个独特的值(value)
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

或者另一种方法是先照顾 NAna.omitcomplete.cases然后使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com