【发布时间】:2019-03-16 02:21:12
【问题描述】:
我有一些看起来像这样的数据:
ID Married Age Visits 1 1 0 35 0 2 2 1 0 7 3 3 0 29 19
df <- data.frame(
ID = c(1L, 2L, 3L),
Married = c(0L, 1L, 0L),
Age = c(35L, 0L, 29L),
Visits = c(0L, 7L, 19L)
)
想象一下,对于这个数据,Married 应该是一个虚拟变量,但Age 和Visits 绝对不应该是 0。我想知道如何做两件事:
- 如何替换,仅在
Age和Visits列中,将 NA 替换为 0 值? - 如何替换,仅在
Age和Visits列中,将 -999 替换为 0 值?这个只是为了好奇,因为我想知道如何在不使用na_if()的情况下做到这一点。
这段代码不太正确,因为它也改变了 Married 列。
df <- na_if(df, 0)
给予:
ID Married Age Visits 1 1 NA 35 NA 2 2 1 NA 7 3 3 NA 29 19
而我想要的是 (1):
ID Married Age Visits 1 1 0 35 NA 2 2 1 NA 7 3 3 0 29 19
和(2):
ID Married Age Visits 1 1 0 35 -999 2 2 1 -999 7 3 3 0 29 19
我尝试了类似的方法:
df <- na_if(c(df$Age, df$Visits), 0))
但这是不对的。
【问题讨论】: