按因子分组的NA计数

时间:2020-04-29 12:17:59

标签: r dplyr

我正在尝试计算每个因素中一列NA的数量。我将使用threshold = 2 for idxDay, row in df.iterrows(): Id = idxDay ratio = row["ratio"] dept = row["dept"] DeptCount=0 MyCount=0 MyLong=0 for idxRange, row1 in df.iterrows(): rangeId = idxRange rangeRatio = row1["ratio"] rangeDept = row1["dept"] if dept== rangeDept and Id != rangeId: DeptCount = DeptCount + 1 if (ratio/rangeRatio) > threshold : MyCount = MyCount + 1 df.loc[idxDay, "higher"]=MyCount 数据框来使其更直观。

enter image description here

查看数据,我想得到一些返回的信息,例如:

mtcars

在SQL术语中,我首先要按mpg count(NA_in_column_carb) 21.0 0 21.4 0 17.3 0 对数据进行分组(在这种情况下,mpg将成为一个因素),然后对mpg值在{ {1}}列。

我尝试使用dplyr编写某些内容,但由于无法产生正确的结果而是产生错误而卡住了。

代码:

NA

错误:

carb

2 个答案:

答案 0 :(得分:1)

您可以sumis.na一起使用:

library(dplyr)
mtcars %>% group_by(mpg) %>% summarise(n = sum(is.na(carb)))

以R为基数的

  1. aggregate

    aggregate(carb~mpg, mtcars, function(x) sum(is.na(x)))
    
  2. tapply

    tapply(mtcars$carb, mtcars$mpg, function(x) sum(is.na(x)))
    

data.table

library(data.table)
setDT(mtcars)[, .(sum = sum(is.na(carb))), mpg]

答案 1 :(得分:0)

我们可以在rowsum中使用base R

rowsum(+(is.na(mtcars$carb)), mtcars$mpg)