【问题标题】:Converting values to NA with conditions in R使用 R 中的条件将值转换为 NA
【发布时间】:2019-06-20 07:43:56
【问题描述】:

我正在尝试将变量转换为带有条件的 NA(缺失)

这是我的数据作为示例。我有 5 个患者 ID,如果 missing 变量中有“1”,outcome1outcome2 将转换为 NA(缺失)。

  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 函数。但是,它没有用。

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函数,你会告诉我的。

【问题讨论】:

  • 在您的示例数据中,没有列 outcome1outcome2。你能显示预期的输出吗?不要忘记set a seed 以获得可重复性。
  • 哦,我犯了严重的错误。我纠正了它。感谢您的关注

标签: r missing-data naniar


【解决方案1】:

如果要替换原地的值,只需使用 ifelse:

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

【讨论】:

  • 替换是对的。我纠正了我的错误。感谢您的帮助。
猜你喜欢
  • 2022-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 2020-11-06
相关资源
最近更新 更多