0

So I have data as such.

d <- structure(c(NA, 1L, 1L, 4L, NA, NA, NA, 1L, 4L, 1L), .Label = c("[1,8]", 
"(8,29]", "(29,105]", "(105,738]"), class = "factor")

So I want to change all NA's to 0 and then plot.

library(ggplot2)

ggplot(data = data.frame(var = d)) +
  geom_bar(aes(x = d), fill = "cornflowerblue")

However I try with the following and it doesn't work...

d <- ifelse(is.na(d) == FALSE, "0", d)
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
John Thomas
  • 1,075
  • 9
  • 32
  • 1
    Does this answer your question? [Set NA to 0 in R](https://stackoverflow.com/questions/10139284/set-na-to-0-in-r) – Jim G. Jul 30 '20 at 17:47

3 Answers3

1

Try this.

levels(d) = append(levels(d), 0)
d[is.na(d)] = 0
ggplot(data = data.frame(var = d)) + geom_bar(aes(x=d), fill="cornflowerblue")
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
Haci Duru
  • 456
  • 3
  • 9
1

there's a couple of issues:

is.na(d) == FALSE is not required, to negate you can use !is.na(d) but since you want to convert NA's you would not want to negate it

secondly you have some issues there because factors are being mixed with other stuff.

you can remove the factors by

d <- levels(d)[d]

then you can remove NAs with

d <- ifelse(is.na(d), "0", d)

finally if you do need the variable to be a factor you can do:

d <- factor(d, ordered = TRUE, levels = c("0", "[1,8]", "(8,29]", "(29,105]", "(105,738]"))

the optional parameter levels was used to prevent some of the levels (that had no records) to be lost

dspn
  • 314
  • 2
  • 9
1

A base solution with addNA()

d <- `levels<-`(addNA(d), c(levels(d), "0"))

#  [1] 0   [1,8]   [1,8]   (105,738]   0   0   0   [1,8]   (105,738]   [1,8]    
# Levels: [1,8] (8,29] (29,105] (105,738] 0

or using the forcats package

d <- forcats::fct_explicit_na(d, "0")

#  [1] 0   [1,8]   [1,8]   (105,738]   0   0   0   [1,8]   (105,738]   [1,8]    
# Levels: [1,8] (8,29] (29,105] (105,738] 0

Then plot again

ggplot(data = data.frame(var = d)) +
  geom_bar(aes(x = var), fill = "cornflowerblue")

According to your comment, you can put "0" in the front by this way

(forcats::fct_relevel() is more flexible than stats::relevel())

ggplot(data = data.frame(var = relevel(d, "0"))) +
  geom_bar(aes(x = var), fill = "cornflowerblue")
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51