Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negation `!` in a dplyr pipeline `%>%`

Tags:

r

dplyr

Is it possible to use negation in dplyr pipeline?

E.g for

df = data.frame(a = c(T,F,F), b = c(T,T,T))

I can write

!df

but I cannot write

df %>% !

(as ! is not a function).

In particular, I use !is.na a lot, but I am not able to incorporate it into pipelines.

like image 253
Piotr Migdal Avatar asked May 10 '15 16:05

Piotr Migdal


2 Answers

You can use backticks around !

 df %>%
       `!`
 #      a     b
 #[1,] FALSE FALSE
 #[2,]  TRUE FALSE
 #[3,]  TRUE FALSE

For !is.na

 df$a[2] <- NA
 df %>% 
      is.na %>% 
      `!`
 #       a    b
 #[1,]  TRUE TRUE
 #[2,] FALSE TRUE
 #[3,]  TRUE TRUE
like image 174
akrun Avatar answered Oct 27 '22 16:10

akrun


Note that the piping operator used in dplyr is imported from magrittr so for access to the other functions, use

library(magrittr)

See the ?extact page for a list of common magrittr-friendly aliases.

In this case not() is defined as a alias for !

df %>% not

To make it easier to call !is.na, you could define

not_ <- function(x, f) not(f(x))
df %>% not_(is.na)
like image 29
MrFlick Avatar answered Oct 27 '22 16:10

MrFlick