获取变量不完全 NA 的唯一 ID 的数量

Get the amount of unique ID's for which a variable is not completely NA

我想知道有多少唯一 NR 具有全部 C_P 个值 NA

DT <- structure(list(NR = c(10001111, 10001111, 10001113, 10001114, 
10001115), C_P = c("8851", "NA", "8873", "NA", "NA"
),        B_LAND = c("NL", "NL", "NL", "NL", "NL")), row.names = c(NA, 
-5L), class = c("data.table", "data.frame"))

         NR  C_P B_LAND
1: 10001111 8851     NL
2: 10001111   NA     NL
3: 10001113 8873     NL
4: 10001114   NA     NL
5: 10001115   NA     NL

我正在努力使语法正确。我试过了;

DT[, .(uniqueNR_without_C_P = uniqueN(is.na(C_P)), by = NR]

所需的输出是 2,因为有两个唯一的 NR,因此没有 C_P

通常你可以这样做:

DT[, all(is.na(C_P)), NR][, sum(V1)]

但由于您的数据中没有 NA 值,只有字符 "NA",您可以这样做:

is_string.NA = function(x) x == "NA"
DT[, all(is_string.NA(C_P)), NR][, sum(V1)]

或者:

uniqueN(DT$NR)  - uniqueN(DT[!is_string.NA(C_P)]$NR)