我有一个数据帧和一些列有NA值。
我如何将这些NA值替换为零?
我有一个数据帧和一些列有NA值。
我如何将这些NA值替换为零?
当前回答
在dplyr 0.5.0中,你可以使用coalesce函数,通过做coalesce(vec, 0)可以很容易地集成到%>%管道中。这将把vec中的所有NAs替换为0:
假设我们有一个带NAs的数据帧:
library(dplyr)
df <- data.frame(v = c(1, 2, 3, NA, 5, 6, 8))
df
# v
# 1 1
# 2 2
# 3 3
# 4 NA
# 5 5
# 6 6
# 7 8
df %>% mutate(v = coalesce(v, 0))
# v
# 1 1
# 2 2
# 3 3
# 4 0
# 5 5
# 6 6
# 7 8
其他回答
取代。数据帧中的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
更通用的方法是在矩阵或向量中使用replace()将NA替换为0
例如:
> x <- c(1,2,NA,NA,1,1)
> x1 <- replace(x,is.na(x),0)
> x1
[1] 1 2 0 0 1 1
这也是在dplyr中使用ifelse()的一种替代方法
df = data.frame(col = c(1,2,NA,NA,1,1))
df <- df %>%
mutate(col = replace(col,is.na(col),0))
另一个使用imputeTS包的例子:
library(imputeTS)
na.replace(yourDataframe, 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`
我想添加一个使用流行的Hmisc包的下一个解决方案。
library(Hmisc)
data(airquality)
# imputing with 0 - all columns
# although my favorite one for simple imputations is Hmisc::impute(x, "random")
> dd <- data.frame(Map(function(x) Hmisc::impute(x, 0), airquality))
> str(dd[[1]])
'impute' Named num [1:153] 41 36 12 18 0 28 23 19 8 0 ...
- attr(*, "names")= chr [1:153] "1" "2" "3" "4" ...
- attr(*, "imputed")= int [1:37] 5 10 25 26 27 32 33 34 35 36 ...
> dd[[1]][1:10]
1 2 3 4 5 6 7 8 9 10
41 36 12 18 0* 28 23 19 8 0*
可以看到,所有的imputation元数据都被分配为属性。因此它可以在以后使用。