Set NA to 0 in R

后端 未结 4 1670
心在旅途
心在旅途 2020-11-29 03:17

After merging a dataframe with another im left with random NA\'s for the occasional row. I\'d like to set these NA\'s to 0 so I can perform calculations with them.

4条回答
  •  情歌与酒
    2020-11-29 03:37

    You can just use the output of is.na to replace directly with subsetting:

    bothbeams.data[is.na(bothbeams.data)] <- 0
    

    Or with a reproducible example:

    dfr <- data.frame(x=c(1:3,NA),y=c(NA,4:6))
    dfr[is.na(dfr)] <- 0
    dfr
      x y
    1 1 0
    2 2 4
    3 3 5
    4 0 6
    

    However, be careful using this method on a data frame containing factors that also have missing values:

    > d <- data.frame(x = c(NA,2,3),y = c("a",NA,"c"))
    > d[is.na(d)] <- 0
    Warning message:
    In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
      invalid factor level, NA generated
    

    It "works":

    > d
      x    y
    1 0    a
    2 2 
    3 3    c
    

    ...but you likely will want to specifically alter only the numeric columns in this case, rather than the whole data frame. See, eg, the answer below using dplyr::mutate_if.

提交回复
热议问题