[英]data.table evaluation 1/0 not equal to TRUE/FALSE
Consider the code snippet:考虑代码片段:
library(data.table)
foo <- data.table(a = rep(c(1, 0), 5), b = c(rep('bar', 5), rep('baz', 5)))
then this is correct:那么这是正确的:
> foo[, sum(b == 'bar')]
[1] 5
But this is not:但这不是:
> foo[, sum(b[a] == 'bar')]
[1] 5
Which could be corrected by:可以通过以下方式纠正:
> foo[, sum(b[a == 1] == 'bar')]
[1] 3
Is 1/0 is not evaluated as TRUE/FALSE in this case?在这种情况下,1/0 是否不被评估为 TRUE/FALSE?
This is a case where printing out intermediate results can help out a lot with what's going on.在这种情况下,打印出中间结果可以对正在发生的事情有很大帮助。
a = rep(c(1, 0), 5)
b = c(rep('bar', 5), rep('baz', 5))
a
#> [1] 1 0 1 0 1 0 1 0 1 0
b
#> [1] "bar" "bar" "bar" "bar" "bar" "baz" "baz" "baz" "baz" "baz"
b[a]
#> [1] "bar" "bar" "bar" "bar" "bar"
b[as.logical(a)]
#> [1] "bar" "bar" "bar" "baz" "baz"
Created on 2019-10-28 by the reprex package (v0.3.0)由代表 package (v0.3.0) 于 2019 年 10 月 28 日创建
By using b[a]
what you're telling R
is that for each element of a
you want the element of b
that corresponds to the index that comes from a
.通过使用
b[a]
您告诉R
的是,对于a
的每个元素,您希望b
的元素对应于来自a
的索引。 And since a
consists of only zeros and ones, you end up just getting the first index 5 times.而且由于
a
仅由零和一组成,因此您最终只会获得第一个索引 5 次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.