df = data.frame("a" = c(1, 2, 3, "q", "r"),
"b" = c(5,6,7,0,"s"))
dfWANT = data.frame("a" = c(1, 2, 3, "NA", "NA"),
"b" = c(5,6,7,0,"NA"))
REP = c("q", "r", "s")
df[,][df[,] == REP] <- NA
我的目的是指定一个列表(REP
),该列表具有要设置为NA
的分数。原始数据是df
,而我想要的是dfWANT
。 REP
是我想设置为NA
的值的向量,最后一行是我的尝试,仅在col a上有效。
您可以使用sapply
根据其中存在TRUE
值来获取FALSE
/ REP
值的逻辑矩阵。然后,我们可以将这些TRUE
值替换为NA
。
df[sapply(df, `%in%`, REP)] <- NA
# a b
#1 1 5
#2 2 6
#3 3 7
#4 <NA> 0
#5 <NA> <NA>
在dplyr
中,我们可以使用mutate_all
library(dplyr)
df %>% mutate_all(~replace(., . %in% REP, NA))
我们可以将data.frame
转换为matrix
并执行%in%
,而无需循环base R
df[`dim<-`(as.matrix(df) %in% REP, dim(df))] <- NA
df
# a b
#1 1 5
#2 2 6
#3 3 7
#4 <NA> 0
#5 <NA> <NA>