简体   繁体   English

如果所有观察结果均为 NA,则按行指示符

[英]Rowwise indicator if all observations are NA

I want to indicate if all observations in a given row are NA .我想指出给定行中的所有观察结果是否都是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.我想创建一个新列( allisna )来指示是否所有观察结果都是 NA。 Note: I want to do this using dplyr (if needed, can use other tidyverse functions, not base R functions like apply() .注意:我想使用dplyr来执行此操作(如果需要,可以使用其他tidyverse函数,而不是像apply()这样的基本 R 函数。

I have the following solution, but I prefer a solution that uses rowwise() and another dplyr function call inside of mutate .我有以下解决方案,但我更喜欢在mutate内部使用rowwise()和另一个dplyr function 调用的解决方案。

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在基础 R 不使用apply你可以做

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编辑以包括@RonakShah 的答案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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