R - 在不计算 NA 的情况下获取每组的值数

R - Get number of values per group without counting NAs

所以我试图在不计算 NA 的情况下计算列中每组值的数量。 我试过用 "length" 来做,但我不知道如何告诉 "length" 在查看每组值的情况下让 NA 保持不变。

我发现了类似的问题,但无法弄清楚如何将解决方案应用到我的案例中:

Length of columns excluding NA in r

http://r.789695.n4.nabble.com/Length-of-vector-without-NA-s-td2552208.html

我创建了一个最小的工作示例来说明问题:

# making some data
value <- c(3,10,9,"NA",5,"NA","NA",4)
group <- c("A","A","B","C","B","A","A","C")

example <- data.frame(value, group)

example
#     value group
# 1     3     A
# 2    10     A
# 3     9     B
# 4    NA     C
# 5     5     B
# 6    NA     A
# 7    NA     A
# 8     4     C


# trying to extract the number of values (without counting NAs) for each group
n.example <- tapply(example$value, list(example$group), length)
n.example
# A B C 
# 4 2 2

#Correct answer would be:
# A B C 
# 2 2 1  

如有任何帮助,我将不胜感激!

谢谢, 嘉玲

如果我们使用的是真正的 NA 而没有引用,我们可以使用 is.natable 来找到计数。

table(!is.na(value), group)[2,]
#A B C 
#2 2 1 

数据

value <- c(3,10,9,NA,5,NA,NA,4)
group <- c("A","A","B","C","B","A","A","C")

可能有更优雅的解决方法,但一种方法是使用匿名函数在获取长度之前删除 NA。

tapply(example$value, example$group, function(x) {length(x[!is.na(x)])})

顺便说一句,您在示例中将 NA 括在引号中。这将导致 R 将 "NA" 视为字符串而不是缺失值。并且您不会通过正确的解决方案获得预期的价值。我相信您正在寻找的示例是

value <- c(3,10,9,NA,5,NA,NA,4)

... 或使用包 dplyr 中的函数过滤和计数:

library(dplyr)
example %>%
    filter(!is.na(value)) %>%
    count(group)

PS:如 akrun 所述,在不带引号的向量中指定 NA。否则值将被转换为字符向量 c("3","10","9","NA",...)