Replace "NA" with values from another column

i have 2 columns: "prop25" and "pm25"

in the column "pm25" I have some "NA", what I want is to replace the "NA" with the values of the column "prop25" and the information that I have in "pm25" does not change, and finally in case of having "NA "in both columns I want to keep the" NA ".

link for the data.frame

Here is one method using the dplyr package.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

DF <- data.frame(prop25 = c(1,2,3,NA, 5), pm25 = c(11,NA, 22, NA, NA))
DF
#>   prop25 pm25
#> 1      1   11
#> 2      2   NA
#> 3      3   22
#> 4     NA   NA
#> 5      5   NA
DF <- DF %>% mutate(pm25 = ifelse(is.na(pm25), prop25, pm25))
DF
#>   prop25 pm25
#> 1      1   11
#> 2      2    2
#> 3      3   22
#> 4     NA   NA
#> 5      5    5

Created on 2021-02-09 by the reprex package (v0.3.0)

1 Like

or coalesce() from the dplyr package

DF <- DF %>% mutate(pm25 = coalesce(pm25, prop25))

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.