我有一个数据帧和一些列有NA值。

我如何将这些NA值替换为零?


当前回答

在data.frame中,不需要通过突变来创建新列。

library(tidyverse)    
k <- c(1,2,80,NA,NA,51)
j <- c(NA,NA,3,31,12,NA)
        
df <- data.frame(k,j)%>%
   replace_na(list(j=0))#convert only column j, for example
    

结果

k   j
1   0           
2   0           
80  3           
NA  31          
NA  12          
51  0   

其他回答

如果我们试图在导出时替换NAs,例如写入csv时,那么我们可以使用:

  write.csv(data, "data.csv", na = "0")

你可以使用replace()

例如:

> x <- c(-1,0,1,0,NA,0,1,1)
> x1 <- replace(x,5,1)
> x1
[1] -1  0  1  0  1  0  1  1

> x1 <- replace(x,5,mean(x,na.rm=T))
> x1
[1] -1.00  0.00  1.00  0.00  0.29  0.00 1.00  1.00

取代。数据帧中的na和NULL。

带列的数据帧

A name(美元是na (A name) < 0美元。

OR

A $ name[是na (A $ name) < - " na "

所有数据帧

自由度[is.na(DF)]<-0

将数据帧中的na替换为空白

df[is.na(df)]<-“”

将NULL替换为NA

df[is.null(df)] <- NA

专用函数nafill和setnafill,用于此目的,在data.table中。 只要可用,它们就将列分发到多个线程上进行计算。

library(data.table)

ans_df <- nafill(df, fill=0)

# or even faster, in-place
setnafill(df, fill=0)

这是一个更灵活的解决方案。不管你的数据帧有多大,它都能工作,或者用0或0来表示0。

library(dplyr) # make sure dplyr ver is >= 1.00

df %>%
    mutate(across(everything(), na_if, 0)) # if 0 is indicated by `zero` then replace `0` with `zero`