Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Change NA values

Tags:

r

na

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!

like image 631
GerritCalle Avatar asked Jan 11 '16 10:01

GerritCalle


People also ask

How to replace Na with specified values in R?

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.

How do I replace Na with 0 in Excel?

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).

How to replace column with missing values using mean in R?

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 −

How do I replace Na with specified values in plyr?

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.


2 Answers

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"
like image 100
Marta Avatar answered Sep 28 '22 04:09

Marta


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.

like image 27
akshay bayas Avatar answered Sep 28 '22 02:09

akshay bayas