Home > database >  How to make !is.na() work with pipes in R?
How to make !is.na() work with pipes in R?

Time:11-17

Sample data i am using to try this out.

df <- data.frame(c1=c(NA,NA,NA,NA,NA,NA,'Account','Liability','NA'),               c2=c('FY','Period','Category','Currency','Location','Entity','Product','Prod1','Prod2'),
                   c3=c('2022','Jan','Group','FX','Location','AUS','*1000',35,45),
                   c4=c(NA,NA,NA,NA,NA,'Brunei','*1000',20,56))

When I try to get the rows that are NA in first column, this works

df %>% select(.,1) %>% is.na()

but if I want to get the non-NAs then adding ! before NA doesn't work

df %>% select(.,1) %>% !is.na()

I suppose it is because !is.na( is not a function by itself.

While !(df %>% select(.,1) %>% is.na()) gives me a result this doesn't help me to add more pipes and operations. Could someone please tell me if there is a way around this?

CodePudding user response:

One option would be to split your operation in two steps like so where you have to wrap ! in backticks. Note also that when using select which returns a df applying is.na() will return a matrix. Perhaps you want pull?

library(dplyr, w = FALSE)

df %>% select(1) %>% is.na() %>% `!`
#>          c1
#>  [1,] FALSE
#>  [2,] FALSE
#>  [3,] FALSE
#>  [4,] FALSE
#>  [5,] FALSE
#>  [6,] FALSE
#>  [7,]  TRUE
#>  [8,]  TRUE
#>  [9,]  TRUE
df %>% pull(1) %>% is.na() %>% `!`
#> [1] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE

And a second option would be to use purrr::negate like so:

df %>% select(1) %>% purrr::negate(is.na)(.)
#>          c1
#>  [1,] FALSE
#>  [2,] FALSE
#>  [3,] FALSE
#>  [4,] FALSE
#>  [5,] FALSE
#>  [6,] FALSE
#>  [7,]  TRUE
#>  [8,]  TRUE
#>  [9,]  TRUE
df %>% pull(1) %>% purrr::negate(is.na)(.)
#> [1] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE
  • Related