我有一个数据帧和一些列有NA值。
我如何将这些NA值替换为零?
我有一个数据帧和一些列有NA值。
我如何将这些NA值替换为零?
当前回答
要替换一个数据帧中的所有NAs,你可以使用:
Df %>% replace(is.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
cleaner包有一个na_replace()泛型,默认情况下将数值替换为0,将逻辑替换为FALSE,将日期替换为今天,等等:
library(dplyr)
library(cleaner)
starwars %>% na_replace()
na_replace(starwars)
它甚至支持矢量化替换:
mtcars[1:6, c("mpg", "hp")] <- NA
na_replace(mtcars, mpg, hp, replacement = c(999, 123))
文档:https://msberends.github.io/cleaner/reference/na_replace.html
DPLYR >= 1.0.0
在dplyr的新版本中:
Across()取代了一系列“作用域变量”,如summarise_at()、summarise_if()和summarise_all()。
df <- data.frame(a = c(LETTERS[1:3], NA), b = c(NA, 1:3))
library(tidyverse)
df %>%
mutate(across(where(anyNA), ~ replace_na(., 0)))
a b
1 A 0
2 B 1
3 C 2
4 0 3
这段代码将强制0为第一列中的字符。要根据列类型替换NA,您可以使用类似呜呜声的公式,其中:
df %>%
mutate(across(where(~ anyNA(.) & is.character(.)), ~ replace_na(., "0")))
更通用的方法是在矩阵或向量中使用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))
不需要使用任何库。
df <- data.frame(a=c(1,3,5,NA))
df$a[is.na(df$a)] <- 0
df