I want to replaces values in a data frame in R with NA based on the occurrence of NAs in a lookup table like the below example.
lookup <- data.frame(date1=c("2018-02-21", "2019-01-14", "2019-01-14", "2019-01-14"),
date2=c("2018-08-22", "2019-01-14", "2019-01-14", NA),
date3=c("2018-10-03", "2019-01-14", NA, NA),
date4=c("2018-10-31", NA, NA, NA)
)
values <- data.frame(val1=c(22.2, 42.1, 38.2, 41.9),
val2=c(23.8, 40.5, 38.5, 39.7),
val3=c(24.2, 39.8, 40.2, NA),
val4=c(27.0,40.1, NA, NA)
)
values_new <- data.frame(val1=c(22.2, 42.1, 38.2, 41.9),
val2=c(23.8, 40.5, 38.5, NA),
val3=c(24.2, 39.8, NA, NA),
val4=c(27.0,NA, NA, NA)
)
CodePudding user response:
We may use
values2 <- values * NA^(is.na(lookup))
Or use
values[is.na(lookup)] <- NA
-checking
> identical(values, values_new)
[1] TRUE