使用 R 中的条件将值转换为 NA [英] Converting values to NA with conditions in R

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

问题描述

我正在尝试使用条件将变量转换为 NA(缺失)

I'm trying to convert variables to NA(missing) with conditions

以我的数据为例.我有 5 个患者 ID,如果 missing 变量中有 '1',outcome1outcome2 将转换为 NA(missing).

This is my data as example. I have 5 patients ID, If there is '1' in missing variable, outcome1 and outcome2 will be converted to NA(missing).

  ID<-c("a","b","c","d","e")
  cond1<-as.factor(sample(x=1:7,size=5,replace=TRUE))
  cond2<-as.factor(sample(x=1:7,size=5,replace=TRUE))
  cond3<-as.factor(sample(x=1:7,size=5,replace=TRUE))
  missing<-as.factor(sample(x=0:1,size=5,replace=TRUE))
  outcome1<-sample(x=1:10, size=5,replace=TRUE)
  outcome2<-sample(x=1:10, size=5,replace=TRUE)
  df<-data.frame(ID,cond1,cond2,cond3,missing,outcome1,outcome2)
  df
   ID cond1 cond2 cond3 missing outcome1 outcome2
1  a     7     1     7       0       6       5
2  b     5     3     7       0       3       1
3  c     4     5     1       1       3       9
4  d     2     2     3       0       7       3
5  e     1     7     4       1       2       7

我在 naniar 包中找到了 replace_with_na_at 函数.然而,它没有奏效.

I've found the replace_with_na_at function, in naniar package. however, it didn't worked.

df%>%
  replace_with_na_at(.vars=c("outcome1","outcome2"), condition = ~ hn10_14med$missing==1)

Error: Predicate functions must return a single `TRUE` or `FALSE`, not a logical vector of length 0
Call `rlang::last_error()` to see a backtrace

如何在条件下将变量转换为 NA?如果有更好的方法,尽管不使用 replace_with_na_at 函数,请告诉我.

How to convert variable to NA with conditions? If there is a better way, though not using replace_with_na_at function, you would let me know.

推荐答案

如果你想就地替换值,只需使用 ifelse:

If you want to replace the values in place, just use ifelse:

df[df$missing==1,c("cond1", "cond2")] <- NA

这篇关于使用 R 中的条件将值转换为 NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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