How do I replace NA values with zeros in an R dataframe?

后端 未结 20 1946
说谎
说谎 2020-11-21 23:41

I have a data frame and some columns have NA values.

How do I replace these NA values with zeroes?

20条回答
  •  迷失自我
    2020-11-22 00:12

    Would've commented on @ianmunoz's post but I don't have enough reputation. You can combine dplyr's mutate_each and replace to take care of the NA to 0 replacement. Using the dataframe from @aL3xa's answer...

    > m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
    > d <- as.data.frame(m)
    > d
    
        V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
    1   4  8  1  9  6  9 NA  8  9   8
    2   8  3  6  8  2  1 NA NA  6   3
    3   6  6  3 NA  2 NA NA  5  7   7
    4  10  6  1  1  7  9  1 10  3  10
    5  10  6  7 10 10  3  2  5  4   6
    6   2  4  1  5  7 NA NA  8  4   4
    7   7  2  3  1  4 10 NA  8  7   7
    8   9  5  8 10  5  3  5  8  3   2
    9   9  1  8  7  6  5 NA NA  6   7
    10  6 10  8  7  1  1  2  2  5   7
    
    > d %>% mutate_each( funs_( interp( ~replace(., is.na(.),0) ) ) )
    
        V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
    1   4  8  1  9  6  9  0  8  9   8
    2   8  3  6  8  2  1  0  0  6   3
    3   6  6  3  0  2  0  0  5  7   7
    4  10  6  1  1  7  9  1 10  3  10
    5  10  6  7 10 10  3  2  5  4   6
    6   2  4  1  5  7  0  0  8  4   4
    7   7  2  3  1  4 10  0  8  7   7
    8   9  5  8 10  5  3  5  8  3   2
    9   9  1  8  7  6  5  0  0  6   7
    10  6 10  8  7  1  1  2  2  5   7
    

    We're using standard evaluation (SE) here which is why we need the underscore on "funs_." We also use lazyeval's interp/~ and the . references "everything we are working with", i.e. the data frame. Now there are zeros!

提交回复
热议问题