我有一个数据帧和一些列有NA值。
我如何将这些NA值替换为零?
我有一个数据帧和一些列有NA值。
我如何将这些NA值替换为零?
当前回答
另一个使用imputeTS包的例子:
library(imputeTS)
na.replace(yourDataframe, 0)
其他回答
我个人用过,效果很好:
players_wd$APPROVED_WD[is.na(players_wd$APPROVED_WD)] <- 0
另一个与tidyrmethod replace_na兼容的dplyr管道选项,适用于多个列:
require(dplyr)
require(tidyr)
m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
d <- as.data.frame(m)
myList <- setNames(lapply(vector("list", ncol(d)), function(x) x <- 0), names(d))
df <- d %>% replace_na(myList)
你可以很容易地限制到例如数字列:
d$str <- c("string", NA)
myList <- myList[sapply(d, is.numeric)]
df <- d %>% replace_na(myList)
这并不是一个新的解决方案,但是我喜欢编写内联lambdas来处理我无法让包完成的事情。在这种情况下,
df %>%
(function(x) { x[is.na(x)] <- 0; return(x) })
因为R不像你在Python中可能看到的那样“通过对象传递”,所以这个解决方案不会修改原始变量df,因此与大多数其他解决方案一样,但是不需要对特定包的复杂知识有太多的要求。
注意函数定义周围的括号!虽然对我来说这似乎有点多余,因为函数定义是用花括号括起来的,但对于magrittr,需要在括号内定义内联函数。
另一个选项使用sapply将所有NA替换为零。下面是一些可重复的代码(数据来自@aL3xa):
set.seed(7) # for reproducibility
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 9 7 5 5 7 7 4 6 6 7
#> 2 2 5 10 7 8 9 8 8 1 8
#> 3 6 7 4 10 4 9 6 8 NA 10
#> 4 1 10 3 7 5 7 7 7 NA 8
#> 5 9 9 10 NA 7 10 1 5 NA 5
#> 6 5 2 5 10 8 1 1 5 10 3
#> 7 7 3 9 3 1 6 7 3 1 10
#> 8 7 7 6 8 4 4 5 NA 8 7
#> 9 2 1 1 2 7 5 9 10 9 3
#> 10 7 5 3 4 9 2 7 6 NA 5
d[sapply(d, \(x) is.na(x))] <- 0
d
#> V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#> 1 9 7 5 5 7 7 4 6 6 7
#> 2 2 5 10 7 8 9 8 8 1 8
#> 3 6 7 4 10 4 9 6 8 0 10
#> 4 1 10 3 7 5 7 7 7 0 8
#> 5 9 9 10 0 7 10 1 5 0 5
#> 6 5 2 5 10 8 1 1 5 10 3
#> 7 7 3 9 3 1 6 7 3 1 10
#> 8 7 7 6 8 4 4 5 0 8 7
#> 9 2 1 1 2 7 5 9 10 9 3
#> 10 7 5 3 4 9 2 7 6 0 5
使用reprex v2.0.2创建于2023-01-15
请注意:从R 4.1.0开始,您可以使用\(x)而不是函数(x)。
我想添加一个使用流行的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元数据都被分配为属性。因此它可以在以后使用。