50

I've been playing around with the airquality dataset in R and figuring out how to remove lines with missing values. I used the following command:

complete.cases(airquality)
AQ1<-airquality[complete.cases(airquality),]

How do I go about replacing the NA's in airquality with 0's and then creating a new dataframe, AQ2?

P.S. Does my command above create a new dataframe called AQ1?

Thanks

killahtron
  • 595
  • 1
  • 4
  • 7

3 Answers3

107
dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] 
[1,]    2    3    5    5    4
[2,]    2    4    3    2    4
[3,]    2   NA   NA   NA    2
[4,]    2    3   NA    5    5
[5,]    2    3    2    2    3
data[is.na(data)] <- 0
m0nhawk
  • 22,980
  • 9
  • 45
  • 73
lbenitesanchez
  • 1,185
  • 1
  • 7
  • 7
27

What Tyler Rinker says is correct:

AQ2 <- airquality
AQ2[is.na(AQ2)] <- 0

will do just this.

What you are originally doing is that you are taking from airquality all those rows (cases) that are complete. So, all the cases that do not have any NA's in them, and keep only those.

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
10

Here are two quickie approaches I know of:

In base

AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1

Not in base

library(qdap)
NAer(airquality)

PS P.S. Does my command above create a new dataframe called AQ1?

Look at AQ1 and see

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • Yes, it does when I look at AQ1. Sorry, I must seem like a real loser asking simple stuff like this, but I'm really new to R. I'm good with stats, just never through a program like this. I've come a long way in the last couple of days though. – killahtron Sep 01 '13 at 20:55
  • 2
    Not at all we start somewhere but the best way I've learned is to try it and see. Everything in R is an object you can look at. Surround objects with `str`, `names` and `summary` and you'll learn a ton of things. – Tyler Rinker Sep 01 '13 at 23:37
  • 1
    Agreed, or put `?` before it to get help documentation on the object, and `??` before it to search for the word in the documentation. – PascalVKooten Sep 02 '13 at 20:56