Rowwise indicator if all observations are NA

I want to indicate if all observations in a given row are NA. For example, with the following data:

dat <- tibble::tribble(
  ~x, ~y, ~z,
  1, 2, NA,
  1, 2, 3,
  NA, NA, NA,
  NA, NA, NA

# A tibble: 4 x 3
      x     y     z
  <dbl> <dbl> <dbl>
1     1     2    NA
2     1     2     3
3    NA    NA    NA
4    NA    NA    NA

I want to create a new column (allisna) to indicate if all observations are NA. Note: I want to do this using dplyr (if needed, can use other tidyverse functions, not base R functions like apply().

I have the following solution, but I prefer a solution that uses rowwise() and another dplyr function call inside of mutate.


dat %>%
  mutate(allisna = apply(tmp, 1, function(x){
    case_when(all( ~ 1,
              TRUE ~ 0)

The final product should be:

# A tibble: 4 x 4
      x     y     z allisna
  <dbl> <dbl> <dbl>   <dbl>
1     1     2    NA       0
2     1     2     3       0
3    NA    NA    NA       1
4    NA    NA    NA       1

Read more here:

Content Attribution

This content was originally published by Brigadeiro at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: