gpt4 book ai didi

r - data.table 使用逻辑列子集行 : why do I have to explicitly compare with TRUE?

转载 作者:行者123 更新时间:2023-12-03 00:10:45 25 4
gpt4 key购买 nike

我想知道为什么对于给定的 data.table:

library(data.table)
DT <- structure(list(number = 1:5, bmask = c(FALSE, TRUE, FALSE, TRUE,
FALSE)), .Names = c("number", "bmask"), row.names = c(NA, -5L
), class = c("data.table", "data.frame"))

> DT
number bmask
1: 1 FALSE
2: 2 TRUE
3: 3 FALSE
4: 4 TRUE
5: 5 FALSE

表达式DT[bmask==T,.(out=number)]按预期工作:

   out
1: 2
2: 4

但是DT[bmask,.(out=number)]导致错误:

> DT[bmask,.(out=number)]
Error in eval(expr, envir, enclos) : object 'bmask' not found

这是 data.table 的正确行为吗?包?

最佳答案

改用这个:

DT[(bmask), .(out=number)]
# out
# 1: 2
# 2: 4
<小时/>

括号的作用是将符号 bmask 放入函数调用内,从其计算环境中,DT 的列将可见1 。任何其他仅返回 bmask 值的函数调用(例如 c(bmask)I(bmask)bmask= =TRUE)或其真实元素的索引(例如 which(bmask))也可以正常工作,但计算时间可能会稍长一些。

如果bmask不在位于函数调用内部,则会在调用范围(此处为全局环境)中搜索它,这有时也很方便。以下是?data.table的相关解释:

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

<小时/>

1要查看 () 本身就是一个函数调用,请输入 is(`(`)

关于r - data.table 使用逻辑列子集行 : why do I have to explicitly compare with TRUE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27989578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com