How to replace variables with NA values with ZERO within a date.frame in R?

Asked

Viewed 5,381 times

3

Let’s say I have a 6x5 data.frame, for example:

print(Dados)

Linha  A   B   C   D   E
L1     4   3   NA  2   4
L2     1   NA  1   NA  1
L3     NA  NA  2   3   4
L4     2   4   5   NA  9

But I want to replace the "NA" values of the data.frame with Zeros, for example:

    Linha  A   B   C   D   E
    L1     4   3   0   2   4
    L2     1   0   1   0   1
    L3     0   0   2   3   4
    L4     2   4   5   0   9

How can I replace variables with NA values by ZERO within my date frame.?

3 answers

5

To replace any column with NA for 0, just do:

Dados[is.na(Dados)] <- 0

  • Thank you for the answer I will test.

5


It is also possible to solve the problem with tidyverse. First, I create a reproducible example:

dataset <- data.frame(
  a = c(NA, 1, NA, 2, 4), 
  b = c(1, 2, 3, NA, NA)
)

With dplyr gets like this:

library(dplyr)

dataset %>% 
  mutate_all(coalesce, 0)

  a b
1 0 1
2 1 2
3 0 3
4 2 0
5 4 0

With tidyr:

library(tidyr)

dataset %>% 
  mutate_all(replace_na, 0)

  a b
1 0 1
2 1 2
3 0 3
4 2 0
5 4 0

Solution r base:

replace(x = dataset, list = is.na(dataset), values = 0)

  a b
1 0 1
2 1 2
3 0 3
4 2 0
5 4 0
  • Thank you for the answer I will test.

1

for example df

you can do so simply without the need to create a column by the mutate command:

library(tidyverse)    
k <- c(1,2,80,NA,NA,51)
j <- c(NA,NA,3,31,12,NA)

df <- data.frame(k,j)%>%
  replace(is.na(.), 0)#coverte todo data.frame
print(df)

outworking

k   j

1   0           
2   0           
80  3           
0   31          
0   12          
51  0   

Browser other questions tagged

You are not signed in. Login or sign up in order to post.