【问题标题】:Finding NA in both variables in R在 R 中的两个变量中找到 NA
【发布时间】:2019-02-10 21:30:24
【问题描述】:

我想通过count()函数在两个长度相同的向量中同时找到NA值的数量:

library(tidyverse)
list1 <-c(NA,NA,3)
list2 <-c(NA,3,4)
count(is.na(list1) & is.na(list2)) # wanna get TRUE 1 FALSE 2 as one only string contains NA values in both variables

它不起作用。存在以下错误:

  Error in UseMethod("groups") : 
  no applicable method for 'groups' applied to an object of class "logical"

但是,我在学习一本相当不错的书之前就成功了。

library(nycflights13) #data-set
flights %>%
count(is.na(arr_delay) & is.na(dep_delay))

在这里有效。似乎有些问题是从某种类型的向量转换为逻辑向量(T 或 F),但我无法弄清楚到底是什么。

【问题讨论】:

  • 你可以试试c(sum(is.na(list1)), sum(is.na(list2)))。我仍然在搞乱count,看看我是否能弄清楚为什么会发生这个错误。

标签: r dplyr tidyverse na


【解决方案1】:

您可以使用table() 构建is.na(list1) &amp; is.na(list2) 中每个逻辑值的计数的列联表:

table(is.na(list1) & is.na(list2))
# FALSE  TRUE 
#     2     1 

【讨论】:

  • 谢谢!看起来挺好的。只是因为我是从不学习经典R,而是从相对较新的库开始的那一代人……
【解决方案2】:

看起来plyrdplyr 都有count() 函数。 plyr 版本基本上说它只是 as.data.frame(table(x)) 的包装器,而 dplyr 看起来它需要 tbl() 作为输入。看来dplyr::count() 是您在上面运行的。

我会在这里使用table(),或者显式调用plyr::count()

library(tidyverse)
list1 <-c(NA,NA,3)
list2 <-c(NA,3,4)
as.data.frame(table(is.na(list1) & is.na(list2)))
#>    Var1 Freq
#> 1 FALSE    2
#> 2  TRUE    1
plyr::count(is.na(list1) & is.na(list2))
#>       x freq
#> 1 FALSE    2
#> 2  TRUE    1
dplyr::count(is.na(list1) & is.na(list2))
#> Error in UseMethod("groups"): no applicable method for 'groups' applied to an object of class "logical"

reprex package (v0.2.1) 于 2019 年 2 月 10 日创建

【讨论】:

  • 谢谢!我想要的样子。
猜你喜欢
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多