简体   繁体   中英

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

# 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 .

library(dplyr)

dat %>%
  mutate(allisna = apply(tmp, 1, function(x){
    case_when(all(is.na(x)) ~ 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

in base R without using apply you can do

dat$allisna <- +(rowSums(!is.na(dat)) == 0)

Figured out one solution (but am open to and will reward more:):

dat %>%
  rowwise() %>%
  mutate(allisna = case_when(all(is.na(c_across(everything()))) ~ 1,
                             TRUE ~ 0))

EDIT to include @RonakShah's answer

dat %>%
  mutate(allisna = as.numeric(rowSums(!is.na(.)) == 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM