I don't get, why glue_data doesn't use a variable available from parent parent environment? See code below. Function test_call_glue_directly
returns desired result. Function test_call_glue
returns error Error in eval(x, envir = data, enclos = envir) : object 'c_1' not found
Of course, my real function has more than one variable. formula_1
might refer to {c_2}
and {c_3}
. Or {c_456}
, {c_7}
, {c_8}
. The count of c_*
might be different.
Is there a way how to create new environment specifically for calling this glue_data? Or pull variable from parent environment? Or some better way how to organize my code? I don't want to pass the parameter c_1
to funciton fill_1
because in my real script there could be unknown count of variables with unknown names.
fill_1 <- function(letts, n0, formula_x) {
purrr::cross_df(list(row = n0, column = letts)) %>%
glue::glue_data(formula_x) %>%
matrix(ncol = length(letts)) %>%
as.data.frame
}
test_call_glue <- function() {
c_1 <- "C"
formula_1 <- "={c_1}{row}"
fill_1(c("A"), c(1:5), formula_1)
}
test_call_glue_directly <- function() {
# The function without wrapping glue_data in function
c_1 <- "C"
formula_1 <- "={c_1}{row}"
purrr::cross_df(list(row = c(1:5), column = c("A"))) %>%
glue::glue_data(formula_1) %>%
matrix(ncol = 1) %>%
as.data.frame
}
test_call_glue_directly()
test_call_glue()
I'm coming back to revisit my question. Since then I have learned to use dots as argument to my custom function:
fill_3a <- function(x, ...) {
paste(paste0(x, c_1), paste0(x, c_2), sep=":::")
}
test_call_paste_a <- function() {
c_1 <- "C"
c_2 <- "H"
ans <- fill_3a("4", c_1, c_2)
return(ans)
}
test_call_paste_a()
Probably it doesn't make sense to call unnamed argument my name, but it makes sense for my use case, where the first argument is string used for glue::glue (variables are substituted to their values by name).