data.table:=变量与列同名时的赋值 [英] data.table := assignments when variable has same name as a column

查看:52
本文介绍了data.table:=变量与列同名时的赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在给一个头寸分配一个值时发现了这种奇怪的行为。如果变量与列具有相同的名称,则认为我们正在谈论该列:

I found this strange behavior when assigning a value to a position. If the variable has the same name as a column it thinks we are talking about the column:

library(data.table)
dt1 <- data.table(a = integer(1))
a <- 18
dt1[1, a:=a]

结果:


> dt1
   a
1: 0


可以通过使用不同的名称来避免这种情况:

We can avoid this by using different names:

dt2 <- data.table(a = integer(1))
b <- 18
dt2[1, a:=b]

结果:


>dt2
    a
1: 18


但是还有另一种方法可以不更改变量名吗?我读到了。()..()表示法,但不确定是否可以在这里使用它,例如:

But is there another way to do this without changing the name of the variable? I read about .() ..() notation but I'm not sure whether I can use it here, something like:

dt1 <- data.table(a = integer(1))
a <- 18
dt1[1, a:=..(a)]

Error in eval(expr, envir, enclos) : could not find function ".."


推荐答案

您始终可以使用 get 来指定环境:

You can always use get, which allows you to specify the environment:

dt1[1, a := get("a", envir = .GlobalEnv)]
#    a
#1: 18

或者只是:

a <- 42
dt1[1, a := .GlobalEnv$a]
#    a
#1: 42

这篇关于data.table:=变量与列同名时的赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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