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

大兔子大兔子 提交于 2021-02-18 20:53:05

问题


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.


回答1:


Why not just move the negation to the "front". This is how you typically negate the %in% infix operatiuon

 !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



回答2:


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



回答3:


Or even

data.frame(data = c(1:2, NA, 4:5, NA, 7)) %>% 
  is.na %>% 
 `n'est pas`


来源:https://stackoverflow.com/questions/25345244/how-to-use-logical-operator-with-magrittr-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!