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
The simple, quick and secure way to send your files around the world without an account. Share your files, photos, and videos today for free.
FJCC
February 10, 2021, 5:08am
2
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)
FJCC:
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
or coalesce() from the dplyr package
DF <- DF %>% mutate(pm25 = coalesce(pm25, prop25))