data.table中的shift()函数的奇怪行为v1.9.5(R) [英] Odd Behavior of shift() function in data.table v1.9.5 (R)

查看:128
本文介绍了data.table中的shift()函数的奇怪行为v1.9.5(R)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的当前开发版本 data.table (v1.9.5),主要是因为它拥有美妙的内置 shift )函数。

I am using the current development version of data.table (v1.9.5), largely because it boasts the wonderful built-in shift() function.

我注意到,当试图对 data.table call - 其中一个是对 shift()的调用 - 我从它得到一些时髦的行为:

I've noticed that, when trying to group statements within a data.table call--one of which being a call to shift()--I get some funky behavior from it:

library(data.table)

foo = data.table(x = c(1, 5, 6 ,2, 9, 8))

foo[, y := {
        delta = c(NA, diff(x));
        lag = shift(x, n = 1L, fill = NA);
        list(delta/lag)}]

上述尝试添加 y 会抛出以下错误:

The above attempt at adding y throws the following error:

Error in delta/lag : non-numeric argument to binary operator

所以我通过创建 delta lag ,而不尝试与它们互动:

So I check what I'm getting by just creating delta and lag without trying to interact them at all:

foo[, c('delta', 'lag') := 
      list(c(NA, diff(x)),
           shift(x, n = 1L, fill = NA))]
foo
   x delta               lag
1: 1   NA  NA, 1, 5, 6, 2, 9
2: 5    4  NA, 1, 5, 6, 2, 9
3: 6    1  NA, 1, 5, 6, 2, 9
4: 2   -4  NA, 1, 5, 6, 2, 9
5: 9    7  NA, 1, 5, 6, 2, 9
6: 8   -1  NA, 1, 5, 6, 2, 9

如果我分开调用,我可以得到我想要的:

If I separate out the calls, I can get exactly what I want:

foo[, delta := c(NA, diff(x))]
foo[, lag := shift(x, n = 1L, fill = NA)]

foo
   x delta lag
1: 1   NA   NA
2: 5    4    1
3: 6    1    5
4: 2   -4    6
5: 9    7    2
6: 8   -1    9

这是一个错误还是我在这里缺少的东西?

Is this a bug or am I missing something here?

编辑:正如Pascal指出的,我的初始示例中的错误是由于 shift()返回一个列表。

As Pascal points out, the error in my initial example is a result of the fact that shift() returns a list.

推荐答案

使用在v1.9.5中的最近提交 shift()返回向量输入上的向量和 length )== 1 。也就是说,当 answer 是长度为1的列表时,为了方便,我们返回一个向量。这允许我们做:

With the recent commit in v1.9.5, shift() returns vector on vector input and length(n) == 1. That is, when the answer is a list of length 1, we return a vector, for convenience. This allows us to do:

DT[, col := shift(val, type = "lead")] # or "lag"

DT[, col := valA + shift(valB, type="lead")] # or "lag"

在这两种情况下,返回一个向量 RHS / code>当原子时,为了方便起见,内部包含 list()

In both cases, a vector is returned and the RHS of := when atomic, is wrapped with list() internally for convenience, and this gives expected behaviour.

这会关闭#1127

这篇关于data.table中的shift()函数的奇怪行为v1.9.5(R)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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