Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NAs in one variable with values from another variable

Tags:

replace

r

How can I replace the "NAs" of a variable VAR1 with with the values of the second variable VAR2 to create a third variable VAR3 in R? The data looks like this:

 VAR1:    VAR2:
 1        NA
 3        NA
 NA       1 
 NA       3
 2        NA 
 NA       1

Afterwards it should look likes this:

 VAR1:    VAR2:    VAR3:
 1        NA       1   
 3        NA       3
 NA       1        1
 NA       3        3
 2        NA       2
 NA       1        1  
like image 482
maller Avatar asked Aug 05 '13 12:08

maller


People also ask

How do I replace NAs with values in R?

dplyr::na_if() to replace specified values with NA s; dplyr::coalesce() to replaces NA s with values from other vectors.

How do you replace Na in a column in a Dataframe?

You can replace NA values with blank space on columns of R dataframe (data. frame) by using is.na() , replace() methods. And use dplyr::mutate_if() to replace only on character columns when you have mixed numeric and character columns, use dplyr::mutate_at() to replace on multiple selected columns by index and name.

How do I overwrite NA in R?

Replace NA with 0 in R Data Frame To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0. myDataframe is the data frame in which you would like replace all NAs with 0.

How do I replace specific values in R?

replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values. It takes on three parameters first is the list name, then the index at which the element needs to be replaced, and the third parameter is the replacement values.


1 Answers

One way is to use ifelse:

DF <- transform(DF, VAR3 = ifelse(!is.na(VAR1), VAR1, VAR2))

where transform was used to avoid typing DF$ over and over, but maybe you will prefer:

DF$VAR3 <- ifelse(!is.na(DF$VAR1), DF$VAR1, DF$VAR2)
like image 86
flodel Avatar answered Nov 15 '22 06:11

flodel