SiH
SiH

Reputation: 1546

Add column to indicate if any other columns contains NA

I have a tibble with lot of NAs. I wish to add a column that shows which is



tbl <- tibble(
  x1 = c(1, 0, NA, 0, NA),
  x2 = c(1, NA, NA, 0, 0),
  x3 = c(1, 0, 0, 0, 1)
)

# add a column z that shows which is true all column values donot contain NA and false if anyone of the column contains NA.

tbl_desired <- tibble(
  x1 = c(1, 0, NA, 0, NA),
  x2 = c(1, NA, NA, 0, 0),
  x3 = c(1, 0, 0, 0, 1),

  z = c(TRUE, FALSE, FALSE, TRUE, FALSE)
)


Upvotes: 1

Views: 47

Answers (1)

akrun
akrun

Reputation: 887128

We could use if_all with complete.cases

library(dplyr)
tbl <- tbl %>%
    mutate(z = if_all(everything(), complete.cases))

-output

tbl
# A tibble: 5 × 4
     x1    x2    x3 z    
  <dbl> <dbl> <dbl> <lgl>
1     1     1     1 TRUE 
2     0    NA     0 FALSE
3    NA    NA     0 FALSE
4     0     0     0 TRUE 
5    NA     0     1 FALSE

Upvotes: 1

Related Questions