Suppose I have a table with a country-year unit, like below, that records information about a few variables (the actual dataset is very large). Some values in some of the columns are missing (not all of cols are affected). However, some of the 'missing' values in the affected columns are really zeros because only non-zero values were initially recorded.
data <- tibble::tibble(country = c(rep("USA",8), rep("MEX",8))
,year = c(1990:1997, 1990:1997)
,var1 = c(1:4, rep(NA, 4), c(3,3,3,3), rep(NA, 4))
,var2 = c(rep(c(rep(1, 6), rep(NA, 2)), 2))
,var3 = c(1:length(country))
,var4 = c(length(country):1)
)
So, I have information regarding when those problematic variables in the data df were observed, such that anything outside these ranges should be NA and anything inside the ranges should be 0:
when_observed <- tibble::tibble(variable = c(rep("var1",6), rep("var2",7))
,year = c(c(1990:1995), c(1990:1996))
)
I need something that will use the information regarding when the variable columns are observed (using when_observed) and fill in those values with zeros in the data df, but without altering actual missing values. It should produce the following table, but at scale (handling multiple column types beyond numerics would be great too):
goal_data <- tibble::tibble(country = c(rep("USA",8), rep("MEX",8))
,year = c(1990:1997, 1990:1997)
,var1 = c(1:4, 0, 0, rep(NA, 2), c(3,3,3,3), 0, 0, rep(NA, 2))
,var2 = c(rep(c(rep(1, 6), 0, NA), 2))
,var3 = c(1:length(country))
,var4 = c(length(country):1)
)
Thanks for any ideas/help.