9

My data looks like this: http://imgur.com/8KgvWvP

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. http://imgur.com/TC1bIgw

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

Marta
  • 2,864
  • 2
  • 15
  • 34
GerritCalle
  • 103
  • 1
  • 1
  • 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

13

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
  • 2,864
  • 2
  • 15
  • 34
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
  • 789,025
  • 32
  • 460
  • 575
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
  • 446
  • 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,594
  • 33
  • 29
  • 34