yenats
yenats

Reputation: 551

Set 0 to NA in R

Opposite to Set NA to 0 in R, I have a data.frame data with columns A and B (and other) in which NAs were replaced by 0 by rowSums(data[,c("A", "B")], na.rm=TRUE).

I need to re-replace all 0 values by NA. As I am working with a data.frame containing not only numeric values, convert all zeros of a matrix in R to NA doesn't work for me (converting into a matrix doesn't seem promising here).

I tried data["A" == 0] <- NA and data["B" == 0] <- NA - however, it doesn't do anything (the data.frame seems to stay unchanged)

Upvotes: 3

Views: 11307

Answers (4)

CPak
CPak

Reputation: 13581

dplyr solution

library(dplyr)
mtcars %>% replace(.==0, NA)

base R solution

replace(mtcars, mtcars==0, NA)

Upvotes: 0

acylam
acylam

Reputation: 18681

Another dplyr solution. This uses mutate_if to only replace zeros with NA's if a column is numeric. B doesn't change because it is a factor/character column.

set.seed(123)
df <- data.frame(A=rep(0:3, 5), B=rep(c("0", "1"), 10), C=c(sample(0:5, 20, replace = TRUE)))

library(dplyr)
df %>%
  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))

You can also use mutate_all if you wish to convert all columns (including facter/character columns):

df %>%
  mutate_all(funs(ifelse(. == 0, NA, .)))

Result:

    A  B  C
1  NA NA  1
2   1  2  4
3   2 NA  2
4   3  2  5
5  NA NA  5
6   1  2 NA
7   2 NA  3
8   3  2  5
9  NA NA  3
10  1  2  2
11  2 NA  5
12  3  2  2
13 NA NA  4
14  1  2  3
15  2 NA NA
16  3  2  5
17 NA NA  1
18  1  2 NA
19  2 NA  1
20  3  2  5

Upvotes: 0

shosaco
shosaco

Reputation: 6165

dplyr solution: data %>% dplyr::mutate(A = ifelse(A == 0, NA, A))

Upvotes: 0

user3640617
user3640617

Reputation: 1576

Is this what you need?

df <- data.frame(A=c(0, 3, "bla"), B=c("A", 0, "X"), C=c("x","B", 4)) #some fake data
df[df == 0] <- NA

Upvotes: 6

Related Questions