GerritCalle
GerritCalle

Reputation: 91

R Change NA values

My data looks like this: https://i.sstatic.net/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.sstatic.net/I9oUw.jpg

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

Upvotes: 9

Views: 44273

Answers (4)

akshay bayas
akshay bayas

Reputation: 11

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.

Upvotes: 1

Marta
Marta

Reputation: 3152

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"

Upvotes: 16

DanieleO
DanieleO

Reputation: 472

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"

Upvotes: 4

akrun
akrun

Reputation: 886938

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)

Upvotes: 5

Related Questions