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

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


当前回答

我本想评论@ianmunoz的帖子,但我没有足够的声誉。你可以结合dplyr的mutate_each和replace来处理NA到0的替换。使用@aL3xa的答案的数据帧…

> 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   4  8  1  9  6  9 NA  8  9   8
2   8  3  6  8  2  1 NA NA  6   3
3   6  6  3 NA  2 NA NA  5  7   7
4  10  6  1  1  7  9  1 10  3  10
5  10  6  7 10 10  3  2  5  4   6
6   2  4  1  5  7 NA NA  8  4   4
7   7  2  3  1  4 10 NA  8  7   7
8   9  5  8 10  5  3  5  8  3   2
9   9  1  8  7  6  5 NA NA  6   7
10  6 10  8  7  1  1  2  2  5   7

> d %>% mutate_each( funs_( interp( ~replace(., is.na(.),0) ) ) )

    V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1   4  8  1  9  6  9  0  8  9   8
2   8  3  6  8  2  1  0  0  6   3
3   6  6  3  0  2  0  0  5  7   7
4  10  6  1  1  7  9  1 10  3  10
5  10  6  7 10 10  3  2  5  4   6
6   2  4  1  5  7  0  0  8  4   4
7   7  2  3  1  4 10  0  8  7   7
8   9  5  8 10  5  3  5  8  3   2
9   9  1  8  7  6  5  0  0  6   7
10  6 10  8  7  1  1  2  2  5   7

我们在这里使用的是标准求值(SE),这就是为什么我们需要在“funs_”上加下划线。我们还使用了lazyeval的interp/~和。引用“我们正在处理的所有东西”,即数据帧。现在有零了!

其他回答

这是一个更灵活的解决方案。不管你的数据帧有多大,它都能工作,或者用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`

这个从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)

如果您想在更改特定列(本例中为列V3)中的NAs后分配一个新名称,也可以这样做

my.data.frame$the.new.column.name <- ifelse(is.na(my.data.frame$V3),0,1)

我本想评论@ianmunoz的帖子,但我没有足够的声誉。你可以结合dplyr的mutate_each和replace来处理NA到0的替换。使用@aL3xa的答案的数据帧…

> 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   4  8  1  9  6  9 NA  8  9   8
2   8  3  6  8  2  1 NA NA  6   3
3   6  6  3 NA  2 NA NA  5  7   7
4  10  6  1  1  7  9  1 10  3  10
5  10  6  7 10 10  3  2  5  4   6
6   2  4  1  5  7 NA NA  8  4   4
7   7  2  3  1  4 10 NA  8  7   7
8   9  5  8 10  5  3  5  8  3   2
9   9  1  8  7  6  5 NA NA  6   7
10  6 10  8  7  1  1  2  2  5   7

> d %>% mutate_each( funs_( interp( ~replace(., is.na(.),0) ) ) )

    V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1   4  8  1  9  6  9  0  8  9   8
2   8  3  6  8  2  1  0  0  6   3
3   6  6  3  0  2  0  0  5  7   7
4  10  6  1  1  7  9  1 10  3  10
5  10  6  7 10 10  3  2  5  4   6
6   2  4  1  5  7  0  0  8  4   4
7   7  2  3  1  4 10  0  8  7   7
8   9  5  8 10  5  3  5  8  3   2
9   9  1  8  7  6  5  0  0  6   7
10  6 10  8  7  1  1  2  2  5   7

我们在这里使用的是标准求值(SE),这就是为什么我们需要在“funs_”上加下划线。我们还使用了lazyeval的interp/~和。引用“我们正在处理的所有东西”,即数据帧。现在有零了!

取代。数据帧中的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