I am trying to do a dplyr::mutate() using case_when to select between various formulas that are assembled from pieces that are strings. However I am clearly not converting the string properly into an expression before quoting and subsequently unquoting them. I have tried seven or eight ways of doing this, all unsuccessful.
The reason for assembling the expression from strings is that I have a large number of groups of variables that have names differing only by a suffix, for example, to distinguish variables in nominal or inflation-adjusted dollars. I use case_when because similar variables have different names, and sometimes different aggregation structures, in different years.
This is a much-simplified example:
bus_inc <- function(tb, suffix) {
bus1 <- quo(paste0("incbus", suffix, " + ", "incfarm", suffix, collapse = ""))
bus2 <- quo(paste0("incbus2", suffix, " + ", "incfarm", suffix, collapse = ""))
bus3 <- quo(paste0("incbus", suffix, " + ", "incfarm2", suffix, collapse = ""))
out <- mutate(tb, bus = case_when((year < 1968) ~ UQ(bus1),
((year > 1967) & (year < 1976)) ~ UQ(bus2),
(year > 1975) ~ UQ(bus3)))
out
}
Data:
incbus_99 <- 1:56
incfarm_99 <- 57:112
incbus2_99 <- incbus_99 + 0.5
incfarm2_99 <- incfarm_99 * 10
year <- 1962:2017
test_tb <- tibble(year, incbus_99, incfarm_99, incbus2_99, incfarm2_99)
my_test <- bus_inc(tb = test_tb, suffix = "_99")
my_test
The value of bus
should be 58 in year 1962 and 70.5 in 1968.
I have found a number of places that suggest parse(text="my_string") as a way of converting a string into an expression, such as this early example (2002) from Martin Maechler. But I have also found a bunch of places that say never to do this, such as Fortune 106 and this recent example from Martin Maechler. I take this forceful repudiation by the formidable Dr. Maechler of a solution he had preciously offered as strong evidence that this is not a good idea, but I do not understand his proposed alternatives, as they seem to evaluate to strings.