TBZ92 - 1 month ago 9

R Question

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`

`f`

`v`

`f`

`l`

`f`

`f==v`

`&`

`sum()`

`l`

`f==v`

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.

Source (Stackoverflow)

Comments