Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute NA by 0 in 20 columns?

Tags:

r

na

I want to substitute NA by 0 in 20 columns. I found this approach for 2 columns, however I guess it's not optimal if the number of columns is 20. Is there any alternative and more compact solution?

mydata[,c("a", "c")] <-
        apply(mydata[,c("a","c")], 2, function(x){replace(x, is.na(x), 0)})

UPDATE: For simplicity lets take this data with 8 columns and substitute NAs in columns b, c, e, f and d

a  b  c  d  e  f  g  d
1  NA NA 2  3  4  7  6
2  g  3  NA 4  5  4  Y
3  r  4  4  NA t  5  5

The result must be this one:

a  b  c  d  e  f  g  d
1  0  0  2  3  4  7  6
2  g  3  NA 4  5  4  Y
3  r  4  4  0  t  5  5
like image 830
Klausos Klausos Avatar asked Oct 11 '15 16:10

Klausos Klausos


People also ask

How do I replace Na with 0 in a column in R?

Replace 0 with NA in an R DataframeUse df[df==0] to check if the value of a dataframe column is 0, if it is 0 you can assign the value NA .

How do I replace Na in multiple columns in R?

Replace NA on Multiple Columns by IndexUse tidyr::replace_na() to update NA values with 0 on selected multiple column indexes. dplyr::mutate_at() takes vector with index numbers and replace_na() replaces all NA with 0 on all multiple indexes specified with vector.

How do you make NA equal 0 in R?

To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0.


1 Answers

Another strategy using tidyr::replace_na()

library(tidyverse)

df <- read.table(header = T, text = 'a  b  c  d  e  f  g  h
1  NA NA 2  3  4  7  6
2  g  3  NA 4  5  4  Y
3  r  4  4  NA t  5  5')

df %>%
  mutate(across(everything(), ~replace_na(., 0)))
#>   a b c d e f g h
#> 1 1 0 0 2 3 4 7 6
#> 2 2 g 3 0 4 5 4 Y
#> 3 3 r 4 4 0 t 5 5

Created on 2021-08-22 by the reprex package (v2.0.0)

like image 92
AnilGoyal Avatar answered Sep 28 '22 09:09

AnilGoyal