跳过data.table中的NA [英] Skip NA in data.table by

查看:82
本文介绍了跳过data.table中的NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 data.table ,但是如果要使用 j 部分,则跳过 by 对应于缺少( NA ):

I'd like to use data.table but would like skip the calculation of the j part if the by corresponds to missing (NA):

此处是示例data.table

Here is an example data.table

library(data.table)
DT <- data.table(y=10, g=c(1,1,1,2,2,2,2,2,NA,NA))

看起来像这样

> DT
     y  g
 1: 10  1
 2: 10  1
 3: 10  1
 4: 10  2
 5: 10  2
 6: 10  2
 7: 10  2
 8: 10  2
 9: 10 NA
10: 10 NA

现在我想对 g by = c>,并将两行9和10合并在一起,因为它们的值 NA

Now I'd like to do the by= on g and the two rows 9 and 10 will be lumped together because they have the same value NA.

> DT[,.N, by=g]
    g N
1:  1 3
2:  2 5
3: NA 2

我想在输出中保留 NA 行,但想跳过计算部分,即得到输出,其中 g N 为空> NA

I'd like to keep the NA line in the output but would want to skip the calculate part in the result, ie., get the output, where N is empty when g is NA

> DT[,.N, by=g]
    g N
1:  1 3
2:  2 5
3: NA NA

我想我可以通过访问 g 的值。GRP,但这仅给出组索引而不是值。是否可以根据 by 变量的缺失状态来进行计算?

I thought I could access the value of g through .GRP but that only gives the group index and not the value. Is it possible to make the calculation conditional on the missing status of the by variable?

推荐答案

您可以尝试以下方法:

DT[, .N * NA^is.na(g), by = g]




    g V1
1:  1  3
2:  2  5
3: NA NA


它是 Henrik的 if ... else ... 子句。
它使用以下事实: NA ^ 0 返回 1 NA ^ 1 返回 NA ,并返回 FALSE TRUE 可以强制为 0 1 ,分别。

It is an algebraic version of Henrik's if ... else ... clause. It uses the fact that NA^0 returns 1 while NA^1 returns NA and that FALSE and TRUE can be coerced to 0 and 1, resp.

如果要控制列名:

DT[, .(n = .N * NA^is.na(g)), by = g]




    g  n
1:  1  3
2:  2  5
3: NA NA


或者,如果上面看起来很棘手,您可以求助于data.table链表(感谢Sotos提出):

Alternatively, if above appears to tricky you can resort to data.table chaining (thanks to Sotos for bringing this up):

DT[, .N, by = g][is.na(g), N := NA][]

这将在聚合后更改 N 的值。

This will change the value of N after aggregation.

这篇关于跳过data.table中的NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆