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!
To replace NA with specified values in R, use the replace_na () function. The replace_na () function replaces NAs with specified values. We can replace it with 0 or any other value of our choice. replace_na (data, replace, ...) data: It is a data frame or Vector. replace: If the data is a Vector, the replace takes a single value.
You can replace 0 with NA only in numeric fields (i.e. excluding things like factors), but it works on a column-by-column basis: With a function, you can apply this to your whole data frame: Although you could replace the 1:5 with the number of columns in your data frame, or with 1:ncol (df).
That means if we have a column which has some missing values then replace it with the mean of the remaining values. In R, we can do this by replacing the column with missing values using mean of that column and passing na.rm = TRUE argument along with the same. Consider the below data frame −
The dplyr package is the next iteration of plyr, focus on tools for working with data frames. The key object in dplyr is a tbl, a representation of a tabular data structure. To replace NA with specified values in R, use the replace_na () function. The replace_na () function replaces NAs with specified values.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With