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
dplyr::na_if() to replace specified values with NA s; dplyr::coalesce() to replaces NA s with values from other vectors.
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.
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.
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.
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)
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