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

1
  • 19
    You can use: airquality[is.na(airquality)] <- 0 Commented Sep 1, 2013 at 20:41

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

3 Comments

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.
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.
Agreed, or put ? before it to get help documentation on the object, and ?? before it to search for the word in the documentation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.