John Paul - 5 months ago 20

R Question

I have run across a situation where

`%>%`

`!`

`x <- c(1:20)`

y <- !is.na(x)

> y

[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

> sum(Y)

[1] 20

Ok, nothing surprising there. But if I try to shorten it using

`%>%`

`!is.na(x) %>% sum`

[1] TRUE

`TRUE`

`20`

If I remove the

`!`

`0`

`> is.na(x) %>% sum`

[1] 0

and if I add brackets it works:

`> {!is.na(x)} %>% sum`

[1] 20

and treating

`!`

`> is.na(x) %>% `!` %>% sum`

[1] 20

What is

`!is.na(x) %>% sum`

`TRUE`

`20`

`> T&T %>% sum()`

[1] TRUE

> {T&T} %>% sum()

[1] 1

> T|T %>% sum()

[1] TRUE

> {T|T} %>% sum()

[1] 1

Answer

I suspect that it's an order of operations issue:

```
!is.na(x) %>% sum
```

is evaluating to

```
!(is.na(x) %>% sum)
```

Which is equivalent to `TRUE`