我有一些看起来像这样的数据:
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
列中替换 0 值的 -999?这只是出于好奇,因为我想知道如何在不使用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))
但那是不对的。
最佳答案
你可以做
解决方案 1)
library(dplyr)
cols <- c("Age", "Visits")
df[cols] <- na_if(df[cols], 0)
df
# ID Married Age Visits
#1 1 0 35 NA
#2 2 1 NA 7
#3 3 0 29 19
解决方案 2)
df[cols][df[cols] == 0] <- -999
df
# ID Married Age Visits
#1 1 0 35 -999
#2 2 1 -999 7
#3 3 0 29 19
与解决方案 2) 类似,您也可以按以下方式执行解决方案 1)
df[cols][df[cols] == 0] <- NA
关于如果 ==0,则仅替换指定列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192855/