0

This is probably a duplicate but I can't find it. I just want to replace 0s with NA in a list of specific columns in my data set, for example, columns 2 and 4:

col1   col2   col3   col4
1       0      4      1
0       3      0      3
5       2      2      0
3       0      2      1

And get:


col1   col2   col3   col4
1       NA     4      1
0       3      0      3
5       2      2      NA
3       NA      2     1


I know how to replace them in one column or for the whole data frame, but how can I do just certain columns?

alex
  • 858
  • 5
  • 14

3 Answers3

2

In tidyverse:

library(dplyr)
library(tidyr)

dat %>% 
  mutate(across(c(col2, col4), ~ na_if(., 0)))

In base R:

sub <- dat[, c("col2", "col4")]
sub[sub == 0] <- NA

or

replace(sub, sub == 0, NA)
Maël
  • 45,206
  • 3
  • 29
  • 67
0

Another dplyr option using matches to only replace the 0 with NA in columns ending with 2 and 4 like this:

df <- read.table(text = "col1   col2   col3   col4
1       0      4      1
0       3      0      3
5       2      2      0
3       0      2      1", header = TRUE)

library(dplyr)
df %>%
  mutate(across(matches("2$|4$"), ~replace(., . == 0, NA)))
#>   col1 col2 col3 col4
#> 1    1   NA    4    1
#> 2    0    3    0    3
#> 3    5    2    2   NA
#> 4    3   NA    2    1

Created on 2022-08-29 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53
0

Using dplyr and tidyr:

your_data %>% mutate(across(col1:col4, ~ if_else(is.na(.x), 0, .x) 
harre
  • 7,081
  • 2
  • 16
  • 28