0

merged$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. It still shows NA in every observation. Also, I have to do this using dplyr.

Galadriel
  • 17
  • 4
  • [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with. That includes a sample of data and all necessary code. Right now, we can't verify the issue because we don't have any data and can't see any output. – camille Oct 30 '19 at 15:25

3 Answers3

3

I know this isn't quite what you are looking for, but you can do this in base R with:

merged$number_articles[is.na(merged$number_articles)] <- 0
Joseph Crispell
  • 395
  • 2
  • 8
2

take a look at ?replace_na for some help.

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.

TTS
  • 1,818
  • 7
  • 16
  • 1
    That would return a vector, but would not replace the original values in the `merged` object. – IRTFM Oct 30 '19 at 15:35
1

R generally (with the data.table exception) requires replacing the starting point with the result of the computation. After reviewing the examples in help(replace_na, pac=tidyr), I suggest:

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

Or:

merged <- merged %>% mutate(
            replace_na( number_articles , 0) )
IRTFM
  • 258,963
  • 21
  • 364
  • 487