Home > Blockchain >  Add column to indicate if any other columns contains NA
Add column to indicate if any other columns contains NA

Time:10-01

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

  • true when all column values do not contain NA and
  • false if anyone of the column contains NA


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)
)


CodePudding user response:

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
  •  Tags:  
  • r
  • Related