9

My data looks like this: https://i.stack.imgur.com/zXk8a.jpg

I want to change the values NA to another value for each column. For example in the column that contains NA, Single and Dual, I want to change all the NA to 'Single'.

I tried this code:

data_price$nbrSims <- ifelse(is.na(data_price$nbrSims), 'Single', data_price$nbrSims)

But then my data looks like this, where Dual became 2 and Single 1. https://i.stack.imgur.com/I9oUw.jpg

How can I change the NA values, without changing the other values? Thanks in advance!

Marta
  • 3,032
  • 3
  • 17
  • 34
GerritCalle
  • 91
  • 1
  • 2
  • 8
  • 4
    don't post images of data. Please consider reading up on [ask] and how to produce a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Heroka Jan 11 '16 at 10:14

4 Answers4

16

Try this (check which are NA and than replace them with "Single"):

data_price$nbrSims <- as.character(data_price$nbrSims)
data_price$nbrSims[is.na(data_price$nbrSims)] <- "Single"
Marta
  • 3,032
  • 3
  • 17
  • 34
  • 1
    This works after data_price$nbrSims <- as.character(data_price$nbrSims) – GerritCalle Jan 11 '16 at 10:23
  • @GerritCalle, I've checked it and it should work without `as.character()`. – Marta Jan 11 '16 at 10:27
  • 2
    @GerritCalle is right: your solution _mostly_ doesn't work. It works only if `Single` is already a `level` of `data_price$nbrSims`. Just try `x<-factor(sample(c(NA,letters[1:4]),100,TRUE));x[is.na(x)]<-"Single"`. Better to convert to `character` beforehand. – nicola Jan 11 '16 at 11:01
  • Thanks for explanation, I agree now. – Marta Jan 11 '16 at 11:07
5

The reason why we got integer values 1 and 2 after the ifelse statement is because the column is a factor class. We convert it to character class and it should work fine

 data_price$nbrSims <- as.character(data_price$nbrSims)
 data_price$nbrSims <- ifelse(is.na(data_price$nbrSims), 
             'Single', data_price$nbrSims)
akrun
  • 874,273
  • 37
  • 540
  • 662
4

Just to be clear, Marta's answer is right.

You can also change all Na Values with this

data_price[is.na(data_price)]<-"Something"
DanieleO
  • 462
  • 1
  • 7
  • 20
1
Data$Mileage <- ifelse( is.na(Data$Mileage),
                        median(Data$Mileage, na.rm = TRUE),
                        Data$Mileage)

In above code, you can change NA value with the median of the column.

David Buck
  • 3,752
  • 35
  • 31
  • 35