如何将指定列中的 0 转换为 NA

How to convert 0 across specified columns to NAs

我有一个数据框:

dat <- data.frame(col1 = sample(0:3, 10, replace = TRUE),
                  col2 = sample(0:3, 10, replace = TRUE),
                  col3 = sample(0:3, 10, replace = TRUE),
                  col4 = sample(0:3, 10, replace = TRUE))

我想将 col1col2col4 中的 0 转换为 NA。我怎样才能做到这一点?大多数例子都是相反的。

谢谢!

您可以使用across忽略col3并使用na_if将0替换为NA

library(dplyr)

dat %>% mutate(across(-col3, na_if, 0))

   col1 col2 col3 col4
1    NA    2    1    3
2     1   NA    0    2
3    NA    1    3    2
4     2   NA    1    3
5     1    1    1    2
6     2    1    0   NA
7     2    3    0    1
8     1    2    0    2
9     3    1    0    3
10    3    2    0    1

数据

dat <- structure(list(col1 = c(0L, 1L, 0L, 2L, 1L, 2L, 2L, 1L, 3L, 3L
), col2 = c(2L, 0L, 1L, 0L, 1L, 1L, 3L, 2L, 1L, 2L), col3 = c(1L, 
0L, 3L, 1L, 1L, 0L, 0L, 0L, 0L, 0L), col4 = c(3L, 2L, 2L, 3L, 
2L, 0L, 1L, 2L, 3L, 1L)), class = "data.frame", row.names = c(NA, 
-10L))

base R中:

dat[-3][dat[-3] == 0] <- NA
#or
replace(dat[-3], dat[-3] == 0, NA)