简体   繁体   English

data.table 评估 1/0 不等于 TRUE/FALSE

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM