'How to convert 0 across specified columns to NAs
I have a dataframe:
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))
I want to convert the 0s in col1, col2 and col4 to NAs. How can I do that? Most examples do the other way around.
Thanks!
Solution 1:[1]
You can use across to ignore col3 and use na_if to replace 0 with 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
Data
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))
Solution 2:[2]
In base R:
dat[-3][dat[-3] == 0] <- NA
#or
replace(dat[-3], dat[-3] == 0, NA)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | benson23 |
| Solution 2 | Maël |
