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

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

问题描述

我在为某个位置赋值时发现了这种奇怪的行为.如果变量与列同名,它认为我们正在谈论该列:

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

结果:

<块引用>

<代码>>dt1一个1:0

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

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

结果:

<块引用>

>dt2一个1:18

但是有没有其他方法可以在不更改变量名称的情况下做到这一点?我读到了 .() ..() 符号,但我不确定我是否可以在这里使用它,例如:

dt1 <- data.table(a = integer(1))a <- 18dt1[1, a:=..(a)]eval 中的错误(expr、envir、enclos):找不到函数.."

解决方案

你总是可以使用get,它允许你指定环境:

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

或者只是:

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

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]

Result:

> dt1
   a
1: 0

We can avoid this by using different names:

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

Result:

>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 ".."

解决方案

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

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

Or just:

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

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

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