Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use logical operator (!) with magrittr in R

Tags:

r

magrittr

I am taking a list of values and trying to find those that are not NA using magrittr. Here is a simple example:

data.frame(data = c(1:2, NA, 4:5, NA, 7)) %>% is.na

which yields the correct result:

      data
[1,] FALSE
[2,] FALSE
[3,]  TRUE
[4,] FALSE
[5,] FALSE
[6,]  TRUE
[7,] FALSE

When I put the not operator ! in front of is.na, I get an error:

data.frame(data = c(1:2, NA, 4:5, NA, 7)) %>% !is.na

gives me

Error in FUN(left, right) : operations are possible only for numeric, logical or complex types

After many trials, I stumbled upon this, which works:

 data.frame(data = c(1:2, NA, 4:5, NA, 7)) %>% is.na %>% !.

      data
[1,]  TRUE
[2,]  TRUE
[3,] FALSE
[4,]  TRUE
[5,]  TRUE
[6,] FALSE
[7,]  TRUE

My question is whether there is a different way to do this. There are other alias options in the package but I don't see any examples of them. One is "not". Maybe I should be using that instead?

I realize that I have answered my question to some degree, but I would like to know if this can be done without having to resort to %>% !. at the end.

like image 556
Mark Danese Avatar asked Aug 17 '14 00:08

Mark Danese


2 Answers

Or even

data.frame(data = c(1:2, NA, 4:5, NA, 7)) %>% 
  is.na %>% 
 `n'est pas`
like image 88
Stefan Avatar answered Oct 07 '22 00:10

Stefan


You can use backticks to pipe your result into the function underlying the operator:

> data.frame(data = c(1:2, NA, 4:5, NA, 7)) %>% is.na %>% `!`
      data
[1,]  TRUE
[2,]  TRUE
[3,] FALSE
[4,]  TRUE
[5,]  TRUE
[6,] FALSE
[7,]  TRUE

Alternatively use the Negate function:

> data.frame(data = c(1:2, NA, 4:5, NA, 7)) %>% Negate(is.na)()
      data
[1,]  TRUE
[2,]  TRUE
[3,] FALSE
[4,]  TRUE
[5,]  TRUE
[6,] FALSE
[7,]  TRUE
like image 39
jdharrison Avatar answered Oct 06 '22 22:10

jdharrison