【问题标题】:R - Get number of values per group without counting NAsR - 获取每组值的数量而不计算 NA
【发布时间】:2015-08-27 14:22:43
【问题描述】:

所以我试图在不计算 NA 的情况下计算列中每组的值数。 我试过用“长度”来做,但在查看每组值的情况下,我不知道如何告诉“长度”让 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  

如果能提供任何帮助,我将不胜感激!

谢谢, 船底座

【问题讨论】:

    标签: r list na tapply


    【解决方案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 应该没有引号。我的错。
    【解决方案2】:

    可能有更优雅的方法可以解决,但一种方法是使用匿名函数在获取长度之前删除 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)
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-10
        • 1970-01-01
        • 2018-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-27
        相关资源
        最近更新 更多