Issue using a list of Booleans to index in R

时间:2019-01-15 18:19:50

标签: r indexing boolean

I've had experience programming for a few years, but am relatively new to R. I ran into an unexpected result when trying to extract an entry from an array using an array of Boolean entries:

array = c(2, 3, 4, 5);
array[c(FALSE, FALSE, FALSE, TRUE)]
#output: [1] 5
array[c(0, 0, 0, 1)]
#output: [1] 2

This surprised me, since I thought FALSE and 0 were interchangeable (likewise for TRUE and 1) in this sort of process. I checked the following to make sure, and became even more confused:

T==1
#output: [1] TRUE
F==0
#output: [1] TRUE
c(0,0,0,1)==c(F,F,F,T)
#output: [1] TRUE TRUE TRUE TRUE

Can someone help explain why R is treating these indexing methods differently?

Much thanks,

1 个答案:

答案 0 :(得分:1)

  

as.logical(c(0,0,0,1))== c(F,F,F,T)

说明

R中,numeric的值与logical的值不同。

在您的情况下,由于2是数组的第一个元素,因此将为第二个子集操作返回它(并且不存在第0个元素)。

PS 仅对于一些操作(例如==),逻辑值首先被强制为数字。感谢@IceCreamTouchan将此添加到上面的注释中。