用R dyplyr有条件地重新编码/替换变量?

编程入门 行业动态 更新时间:2024-10-27 12:27:26
本文介绍了用R dyplyr有条件地重新编码/替换变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用以下代码有条件地重新编码我的变量,以便在 var1 中存在大于 0 的任何值时,将 var 2 中的值替换为 NA.如果 var1 没有大于 0 的值(编码为 NA),则 var2 中的值应保持原样.下面的代码行将 var2 中的所有内容编码为 NA,如果 var1 为 NA,则不保留 var2 中的值.我也尝试使用 na_if() 和 coalesce() ,但没有太大成功.有没有可能解决这个问题?

I am trying to use the following code to recode my variables conditionally so that the values in var 2 are replaced by NA if there is any value greater than 0 in var1. If var1 has no value greater than 0 (which is coded as NA), then the value in var2 should remain as it is. The line of code below codes everything in var2 to NA and does not keep the values in var2 if var1 is NA. I have also tried to use na_if() and coalesce() with not much success. Any possible fix to this?

df <- df %>% mutate(var2 = if_else(var1 > 0, NA, var2 = TRUE ))

推荐答案

我们不需要 var2 = TRUE,而应该是 var2

We don't need var2 = TRUE, instead it should be var2

library(dplyr) df %>% mutate(var2 = ifelse(var1 > 0, NA, var2))

if_else 是特定于类型的,因此您需要具有与 'var2' 类型匹配的正确 NA 类型.假设它是 numeric :

if_else is type specific, so you need to have the correct NA type matching the 'var2' type. Assuming it is numeric :

df %>% mutate(var2 = if_else(var1 > 0, NA_real_, var2))

但是,这也可以通过:

But, this can be also done with :

df %>% mutate(var2 = replace(var2, var1 > 0, NA))

或者使用 case_when :

df %>% mutate(var2 = case_when(var1 > 0 ~ NA_real_, TRUE ~ var2))

更多推荐

用R dyplyr有条件地重新编码/替换变量?

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

发布评论

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

>www.elefans.com

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