R Change NA values
Asked Answered
rna
G

4

9

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!

Guthry answered 11/1, 2016 at 10:7 Comment(1)
don't post images of data. Please consider reading up on How to Ask and how to produce a reproducible example.Pinnace
S
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"
Scientistic answered 11/1, 2016 at 10:10 Comment(4)
This works after data_price$nbrSims <- as.character(data_price$nbrSims)Guthry
@GerritCalle, I've checked it and it should work without as.character().Scientistic
@Guthry 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.Brownedoff
Thanks for explanation, I agree now.Scientistic
B
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)
Benzol answered 11/1, 2016 at 10:13 Comment(0)
W
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"
Wingspan answered 11/1, 2016 at 10:15 Comment(0)
D
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.

Disgust answered 26/4, 2020 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.