R:使用 tidyverse 将 NA 替换为 df 中的其他变量 [英] R: Replace NA with other variables in the df using tidyverse

查看:32
本文介绍了R:使用 tidyverse 将 NA 替换为 df 中的其他变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 tidyverse 替换我的 df 中的 NA 值,我想要的值应该从其他列计算:

I want to replace the NA values in my df using tidyverse, the values I want should be caculated from other cols:

输入:

ID,    X1,    X2,    X3,
"A",  0.96,   NA,    0.97,
"B",  1.00,   NA,    1.01,
"C",  0.98,   0.03,  NA,
"A",  1.00,   NA,    1.00,
"D",  NA,     0.05,  0.99,

我希望在每一行中找出所有三个 X1, X2, X3 中的哪个变量是 NA 并用其他两个变量的总和计算它

My wish is to find in each row which variable of all three X1, X2, X3 is NA and to calcualte it with the sum of the other two variables

输出:

ID,    X1,    X2,    X3,
"A",  0.96,   1.93,  0.97,
"B",  1.00,   2.01,  1.01,
"C",  0.98,   0.03,  1.01,
"A",  1.00,   2.00,   1.00,
"D",  1.04,   0.05,  0.99,

谢谢!

推荐答案

非常好的问题.谢谢!

这里我们使用:

  1. rowSums 添加一列,行和为 X1-X3
  2. 然后我们mutate 所有X
  3. coalesce 每个 XrowSum1
  4. 令人惊讶的是 rowSum1 列因为不需要而消失了 ->
  5. 这是由于 .keep="unused"mutate
  6. 参数
  1. rowSums to add a column with the row sums of X1-X3
  2. then we mutate across all X and
  3. coalesce each X with rowSum1
  4. surprisingly rowSum1 column is gone away because not needed ->
  5. this is due to the fantastic .keep="unused" argument of mutate

library(tidyverse)
df %>% 
  mutate(rowsum1 = rowSums(select(., starts_with("X")), na.rm=TRUE)) %>% 
  mutate(across(starts_with("X"), ~coalesce(.,rowsum1)),.keep="unused")

输出:

  ID       X1    X2    X3
  <chr> <dbl> <dbl> <dbl>
1 A      0.96  1.93  0.97
2 B      1     2.01  1.01
3 C      0.98  0.03  1.01
4 A      1     2     1   
5 D      1.04  0.05  0.99

这篇关于R:使用 tidyverse 将 NA 替换为 df 中的其他变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆