问题
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