且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R:使用 tidyverse 将 NA 替换为 df 中的其他变量

更新时间:2023-02-18 11:20:16

非常好的问题.谢谢!

这里我们使用:

  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