1

I was experimenting with the pipe function from dplyr, and running below code without success -

library(dplyr)
12 %>% ifelse(is.na(.), FALSE, TRUE)
### Error in ifelse(., is.na(.), FALSE, TRUE) : unused argument (TRUE)

Any pointer why I am getting this error? What is the correct approach if I want to use pipe?

Bogaso
  • 2,838
  • 3
  • 24
  • 54
  • 6
    A similar situation was discussed recently https://stackoverflow.com/questions/60106626/piping-a-vector-into-all-to-test-equality/60106676#60106676 – tmfmnk Feb 07 '20 at 12:55
  • Please think about the value of logical conditions, such as `is.na`, before coding constructs like `ifelse(logical_condition, FALSE, TRUE)`. The result of `logical_condition` **already is a logical value**. – Rui Barradas Feb 07 '20 at 13:03
  • @RuiBarradas In my code I was trying convert a NA to FALSE to eliminate the chance of any break in subsequent codes – Bogaso Feb 07 '20 at 13:12
  • 1
    Does this answer your question? [Using the %>% pipe, and dot (.) notation](https://stackoverflow.com/questions/42385010/using-the-pipe-and-dot-notation) – Brian Feb 07 '20 at 14:19
  • OK, but something like `%>% mutate(new_value = !is.na(.))` is better. – Rui Barradas Feb 07 '20 at 15:54

4 Answers4

2

Another option is to unnest the functions further.

12 %>% is.na %>% ifelse(FALSE, TRUE)
# TRUE
AndS.
  • 7,748
  • 2
  • 12
  • 17
2

We can use is.na directly in the pipeline rather than nesting it:

12 %>% is.na %>% ifelse(FALSE, TRUE)

or

12 %>% is.na %>% `!`

or

library(magrittr)
12 %>% is.na %>% not

or

12 %>% (is.na %>% Negate)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

There are several possibilities:

Using brackets: As @tmfmnk pointed out, one should use {} to get that behavior in pipe:

 library(dplyr)
 vec <- c(12,13, NA)
 vec %>% {ifelse(is.na(.), FALSE,TRUE)}
 # TRUE  TRUE FALSE

Unnesting: Alternatively, as @Ands pointed out, one can unnest the functions:

12 %>% is.na %>% ifelse(FALSE, TRUE)
Carles
  • 2,731
  • 14
  • 25
0
library(dplyr)
12 %>% ifelse(is.na(.), FALSE)
#FALSE

this works for me

Carbo
  • 906
  • 5
  • 23