R-在不计算NA的情况下获取每组的值数 [英] R - Get number of values per group without counting NAs
问题描述
因此,我试图计算一列中每个组的值数量,而不计算NA. 我尝试使用长度"来执行此操作,但是在查看每个组的值时,我无法弄清楚如何告诉长度"保持NA.
So I'm trying to count the number of values per group in a column without counting the NAs. I've tried doing it with "length" but I can't figure out how to tell "length" to leave the NAs be, when in the context of looking at values per group.
我发现了类似的问题,但不知道如何将解决方案应用于我的案子:
I've found similar problems but couldn't figure out how to apply the solutions to my case:
http://r .789695.n4.nabble.com/Length-of-vector-without-NA-s-td2552208.html
我创建了一个最小的工作示例来说明问题:
I've created a minimal working example to illustrate the problem:
# 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
我将不胜感激!
Thx, 船长
推荐答案
如果我们使用不带引号的真实NA,则可以使用is.na
和table
来查找计数.
If we are using real NAs without quoting, we can use is.na
and table
to find the count.
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")
这篇关于R-在不计算NA的情况下获取每组的值数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!