简体   繁体   English

使用 dplyr 在 R 中将列中的所有 NA 值替换为 0

[英]replacing all NA values in a column with 0 in R using dplyr

merged$number_articles %>% replace_na(0)合并$number_articles %>% replace_na(0)

Im trying to replace all na values in a column (number_articles) in the df (merged), with 0. I have tried the above code but the values are not getting replaced.我试图用 0 替换 df(合并)中列(number_articles)中的所有 na 值。我已经尝试了上面的代码,但这些值没有被替换。 It still shows NA in every observation.它仍然在每次观察中显示 NA。 Also, I have to do this using dplyr.此外,我必须使用 dplyr 来执行此操作。

I know this isn't quite what you are looking for, but you can do this in base R with:我知道这不是您要寻找的,但是您可以在基础 R 中执行此操作:

merged$number_articles[is.na(merged$number_articles)] <- 0

take a look at?replace_na for some help.看看?replace_na 以获得一些帮助。

This should work:这应该有效:

merged <- merged %>%
   mutate(number_articles = replace_na(number_articles, 0))

EDIT: modified to include in a mutate, which I believe solves the issue identified by 42 in comments.编辑:修改为包含在 mutate 中,我相信这可以解决 42 在评论中确定的问题。

R generally (with the data.table exception) requires replacing the starting point with the result of the computation. R 通常(除了 data.table 例外)需要用计算结果替换起点。 After reviewing the examples in help(replace_na, pac=tidyr), I suggest:在查看了 help(replace_na, pac=tidyr) 中的示例后,我建议:

library(tidyr)  # or library(tidyverse)
merged <- merged %>% 
            replace_na( list(number_articles =0) )

Or:或者:

merged <- merged %>% mutate(
            replace_na( number_articles , 0) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM