在data.table中多次使用:= [英] Using := multiple times in data.table

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

问题描述

我经常发现自己在同一数据表上使用:= 进行了一系列的链式计算。例如,类似这样的

I frequently find myself doing a long series of chained calculations using := on the same data table. For example, something like this

test = data.table(1:10, 1:10, 1:10, 1:10)

test[, V1 := V1^2]
test[, V2 := V1*V2]
test[, V3 := V2/V3]
test[, V4 := sqrt(V3)]
test[, new := letters[V4]]

必须在每行1上写 test [,...] 需要更长的时间键入(这不是我可以应付的大问题) 。但是,更重要的是,还从视觉上分散了计算的流程和内容。我宁愿写这样的东西

Having to write test[, ...] on every line 1) takes longer to type (not a big issue I can cope with that). But, more importantly, also distracts visually from the flow and content of the calculation. I would much rather write something like

test[, {
  V1 := V1^2
  V2 := V1*V2
  V3 := V2/V3
  V4 := sqrt(V3)
  new := letters[V4]
}]

但这会引发的错误,您已经用{}包裹了:=,但是:=必须是{} 中唯一的东西。

But this throws an error of You have wrapped := with {} which is ok but then := must be the only thing inside {}.

我知道我会写

within(test, {
  V1 = V1^2
  V2 = V1*V2
  V3 = V2/V3
  V4 = sqrt(V3)
  new = letters[V4]
  })

但这会降低使用:=

我尝试编写一个提供此功能的函数

I tried writing a function to provide this ability

with.dt = function(dt, expressions){
  e = strsplit(expressions,'\n')
  for (i in 1:length(e)){    
    dt[, eval(parse(text = e[i]))]
  }
  dt
  }

with.dt(test, "
  V1 := V1^2;
  V2 := V1*V2;
  V3 := V2/V3;
  V4 := sqrt(V3);
  new := letters[V4];
  ")

但这不会更改数据的内容。表

But this does not change the content of the data.table

是否有任何语法允许 c版本内的外观整洁,同时保留<$的按引用分配属性c $ c>:=

Is there any syntax that permits the neat look of the within version, while retaining the assign by reference property of :=?

推荐答案

有两种不同的方法可以做到这一点。

There are a couple different ways to do this.

这里使用的原始测试矩阵:

Original test matrix used here:

   v1 v2
1:  1  3
2:  2  4

首先,我们可以做这样的事情:

First, we can do something like this:

test[,`:=`(v1 = v1^2,
          v2 = v1*v2)

输出:

v1 v2
 1  3
 4  8

或者,如果

test[, `:=`(v1 = v1 <- v1^2, v2 = v2 * v1)]

输出:

v1 v2
 1  3
 4 16  

或者,我们可以类似地运行它:

Or, similarly we could run this:

test[,c("v1","v2") := list(v1^2,v1^2*v2)]

输出:

v1 v2
 1  3
 4 16

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

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