-1

First, how do I change NA into anything?

x[x==NA] <- "anything"

This does not work.

Also, how do I delete a row in a dataframe with condition on NA? For example:

    [,1][,2][,3]
[1,]  NA  NA 284
[2,] 233 182 249
[3,] 177 201  NA

I want to delete the row which has 2 or more NA in that particular row, so it will result in:

    [,1][,2][,3]
[2,] 233 182 249
[3,] 177 201  NA

Someone marked my question duplicated, but actually I want to control the amount of NA to delete a row, complete.cases(x) cannot provide any control to it.

Henry Li
  • 11
  • 2
  • 2
    I appreciate that you might have been unclear in your own mind as to what you wanted, but it's a little bit cheesy to change your question after it's been answered. I've added a solution to your (updated) problem to @RHertel's answer ... – Ben Bolker Jan 28 '16 at 22:44
  • PS http://thomasleeper.com/Rcourse/Tutorials/NAhandling.html – Ben Bolker Jan 28 '16 at 22:52

4 Answers4

2

You can also use complete.cases():

x <- x[complete.cases(x),]
HubertL
  • 19,246
  • 3
  • 32
  • 51
1

Here's another possibility:

x[!is.na(rowSums(x)),]
#[1] 233 182 249

data

x <- matrix(c(NA , NA, 284, 233, 182, 249, 177, 201, NA), byrow=TRUE, ncol=3)

To control the tolerance for NA values (e.g. exclude only rows with at least 2 NA values):

x[rowSums(is.na(x))<2,]
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
RHertel
  • 23,412
  • 5
  • 38
  • 64
0

To replace NAs:

x[which(is.na(x))] <- 0  # will be replaced by 0

To remove rows with two or more NA using apply function:

x[-which(apply(x, 1, function(xx) length(which(is.na(xx)))) >= 2),]
Pandya21
  • 61
  • 6
0

I think the others answer the 2nd part of your question. To answer your first part.

If x is a vector

x <- c(1,2,3,NA,4,NA)
x[is.na(x)] <- "anything"

If x is a data frame

x <- c(1,1,1,NA,1,NA)
df <- data.frame(var1=x,var2=x)
df$var1[is.na(df$var1)] <- -1
Matt L.
  • 397
  • 4
  • 12