子集数据表由逻辑列

问题描述:

我有一个带有逻辑列的 data.table 。为什么逻辑列的名称不能直接用于 i 参数?参见示例。

I have a data.table with a logical column. Why the name of the logical column can not be used directly for the i argument? See the example.

dt <- data.table(x = c(T, T, F, T), y = 1:4)

# Works
dt[dt$x]
dt[!dt$x]

# Works
dt[x == T]
dt[x == F]

# Does not work
dt[x]
dt[!x]


?data.table


高级:当i是单个变量名时,不会被视为列名的
表达式,

Advanced: When i is a single variable name, it is not considered an expression of column names and is instead evaluated in calling scope.

因此 dt [x] 会尝试在调用范围(在这种情况下是全局环境)中 x 进行求值

So dt[x] will try to evaluate x in the calling scope (in this case the global environment)

{ force

dt[(x)]
dt[{x}]
dt[force(x)]