library(rlang)
library(dplyr)
library(lubridate)
example = tibble(
date = today() + c(1:6),
foo = rnorm(6),
)
do.some.stuff <- function(data, foo.col){
sum.col = parse_expr(paste(expr_text(enexpr(foo.col)), "sum", sep="."))
max.col = parse_expr(paste(expr_text(enexpr(foo.col)), "max", sep="."))
cnt.col = parse_expr(paste(expr_text(enexpr(foo.col)), "cnt", sep="."))
select(data, date, {{ foo.col }}) %>%
filter(!is.na(date) & !is.na({{ foo.col }})) %>% mutate(
"{{ foo.col }}.cnt" := cumsum( !is.na({{ foo.col }}) ),
"{{ foo.col }}.sum" := cumsum({{ foo.col }}),
"{{ foo.col }}.max" := cummax( {{ sum.col }} ),
"{{ foo.col }}.mu" := {{ sum.col }} / {{ cnt.col }}
)
}
do.some.stuff(example, foo)
So the above code works just fine, but it is kind of ugly, particularly the three parse_expr lines. i could rewrite the function as:
do.some.stuff <- function(data, foo.col){
sum.col = paste(expr_text(enexpr(foo.col)), "sum", sep=".")
max.col = paste(expr_text(enexpr(foo.col)), "max", sep=".")
cnt.col = paste(expr_text(enexpr(foo.col)), "cnt", sep=".")
select(data, date, {{ foo.col }}) %>%
filter(!is.na(date) & !is.na({{ foo.col }})) %>% mutate(
cnt.col := cumsum( !is.na({{ foo.col }}) ),
sum.col := cumsum({{ foo.col }}),
max.col := cummax( {{ parse_expr(sum.col) }} ),
"{{ foo.col }}.mu" := {{ parse_expr(sum.col) }} / {{ parse_expr(cnt.col) }}
)
}
But it's not a lot better. Is there any other ways to do accomplish this same behavior (I don't want to change the shape of the df, that part is not up to me) but kick the rlang dependency? This works just fine for now but I would like something cleaner / easier to read if it is possible. If it wasn't obvious, I am newish to metaprogramming in R although I do have experience in other languages.