我有一个数据帧和一些列有NA值。
我如何将这些NA值替换为零?
我有一个数据帧和一些列有NA值。
我如何将这些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))
其他回答
另一个选项使用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)。
这并不是一个新的解决方案,但是我喜欢编写内联lambdas来处理我无法让包完成的事情。在这种情况下,
df %>%
(function(x) { x[is.na(x)] <- 0; return(x) })
因为R不像你在Python中可能看到的那样“通过对象传递”,所以这个解决方案不会修改原始变量df,因此与大多数其他解决方案一样,但是不需要对特定包的复杂知识有太多的要求。
注意函数定义周围的括号!虽然对我来说这似乎有点多余,因为函数定义是用花括号括起来的,但对于magrittr,需要在括号内定义内联函数。
另一个与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)
这个从Datacamp中提取的简单函数可以帮助:
replace_missings <- function(x, replacement) {
is_miss <- is.na(x)
x[is_miss] <- replacement
message(sum(is_miss), " missings replaced by the value ", replacement)
x
}
Then
replace_missings(df, replacement = 0)
也可以使用tidyr::replace_na。
library(tidyr)
df <- df %>% mutate_all(funs(replace_na(.,0)))
编辑(dplyr > 1.0.0):
df %>% mutate(across(everything(), .fns = ~replace_na(.,0)))