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

编程入门 行业动态 更新时间:2024-10-27 13:32:40
本文介绍了R:使用 tidyverse 将 NA 替换为 df 中的其他变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想使用 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,

谢谢!

推荐答案

非常好的问题.谢谢!

这里我们使用:

rowSums 添加一列,行和为 X1-X3然后我们mutate 所有Xcoalesce 每个 XrowSum1令人惊讶的是 rowSum1 列因为不需要而消失了 ->这是由于 .keep="unused"mutate 参数 rowSums to add a column with the row sums of X1-X3 then we mutate across all X and coalesce each X with rowSum1 surprisingly rowSum1 column is gone away because not needed -> 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 13:27:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1395113.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   tidyverse   NA   df

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!