Josh
Josh

Reputation: 1337

is.na gives unexpected result when used after magrittr pipe %>%

I'm using == to compare two character vectors, one of which contains NA elements. I then want to pipe the logical output of == to is.na using the magrittr pipe operator %>%. When I do this directly I get an unexpected result. When I bracket the == comparison with (...), or save the output of == to an object, the piping works. What am I missing about the function of either %>% or is.na? Thanks.

cvglists <- structure(
  list(NULL, NULL, NULL, NULL, NULL), 
  names = c("x", "y", "z", NA, NA)
)
bw_use <-  list(
  x = "bigwig_nos", 
  y = "bigwig_nos", 
  z = "bigwig_nos", 
  a = "bigwig_nos", 
  b = "bigwig_nos"
)
names(cvglists) == names(bw_use)[1:length(cvglists)] %>% is.na()
[1] FALSE FALSE FALSE    NA    NA                                   ## unexpected
(names(cvglists) == names(bw_use)[1:length(cvglists)]) %>% is.na()
[1] FALSE FALSE FALSE  TRUE  TRUE                                   ## expected
## work around
tmp <- names(cvglists) == names(bw_use)[1:length(cvglists)]
tmp %>% is.na()
[1] FALSE FALSE FALSE  TRUE  TRUE                                   ## expected

EDIT: I'm pretty sure the issue is my intended RHS of == is being piped to is.na, and then the ouput of is.na is being used as the RHS of == (see code below).

> names(cvglists) == (names(bw_use)[1:length(cvglists)] %>% is.na())
[1] FALSE FALSE FALSE    NA    NA                                   ## unexpected
> (names(cvglists) == names(bw_use)[1:length(cvglists)]) %>% is.na()
[1] FALSE FALSE FALSE  TRUE  TRUE                                   ## expected

I found these explanations: https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html Order of operation with piping

Upvotes: 1

Views: 25

Answers (0)

Related Questions