简体   繁体   English

当 R 中的所有值均为 NA 时,重新编码并求和为 NA

[英]Recode and sum to NA when all values are NA in R

I need to assign NA when all the columns are empty in summation for each id .当每个id的总和中所有列都为空时,我需要分配NA

Here is how my sample dataset looks like;这是我的示例数据集的样子;

df <- data.frame(id = c(1,2,3),
                 i1 = c(1,NA,0),
                 i2 = c(1,NA,1),
                 i3 = c(1,NA,0),
                 total = c(3,0,1))

> df
  id i1 i2 i3 total
1  1  1  1  1     3
2  2 NA NA NA     0
3  3  0  1  0     1

For the second id the total should be NA instead of 0 because all the values are NA for the second id.对于第二个id ,总数应该是NA而不是 0,因为第二个 id 的所有值都是 NA。 How can I change the dataset to below?如何将数据集更改为以下内容?

  > df1
      id i1 i2 i3 total
    1  1  1  1  1     3
    2  2 NA NA NA     NA
    3  3  0  1  0     1

We could create a condition with if_all in case_when to return NA when all the column values are NA for a row or else do the rowSums with na.rm = TRUE我们可以在case_when中使用if_all创建一个条件,当一行的所有列值均为 NA 时返回NA ,或者使用na.rm = TRUE执行rowSums

library(dplyr)
df %>%
   mutate(total = case_when(if_all(i1:i3,  is.na) ~ NA_real_,
        TRUE ~ rowSums(across(i1:i3), na.rm = TRUE)))

-output -输出

  id i1 i2 i3 total
1  1  1  1  1     3
2  2 NA NA NA    NA
3  3  0  1  0     1

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

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