TBZ92 TBZ92 - 2 months ago 14
R Question

What is the behavior of the ampersand operator in R's sum(...) function

Below, a line from a script I'm translating from R into Python. I'm more experienced at Python than I am at R, and I'm running into a little trouble here:

val = sum(l & f==v)


Let
l
be a vector of true/false values. Let
f
be a vector of trivial values, and
v
some possible value of
f
to test against. I expect
l
and
f
to be of the same length. The
f==v
part will also yield a boolean array. Now I am left with the question what the
&
/ampersand (Logical AND, according to the R documentation) will do in this context. Will the
sum()
function return the sum of a boolean array that indicates where both the
l
and
f==v
boolean arrays are true? Or wil it sum all true values for both arrays and add them up?

Thank you in advance!

Answer

Let define several vectors :

l <- c(TRUE, FALSE, TRUE, FALSE, TRUE)
v <- 1:5
f <- rep(c(1, 4), c(3, 2))

now let see what we have when we decompose your line sum(l & f==v):
In this line, == has precedence over &:

fev <- f==v
fev
[1]  TRUE FALSE FALSE  TRUE FALSE

Then we do l & fev:

lafev <- l & fev
[1]  TRUE FALSE FALSE FALSE FALSE

lastly, we sum:

sum(lafev)
[1] 1

The sum tells us how many simultaneous TRUE there are in l and f==v by converting the logical values to numeric: TRUE becomes 1 and FALSE becomes 0. So, in this example, 1.