I'm doing a for
inside a function using rlang
but it doesn't work.
using r base it works
library(rlang)
library(dplyr)
library(R.utils)
db <- tibble(
CRT1 = 15*rnorm(10),
CRT2 = 12*rnorm(10))
f <- function(df, controls) {
for (i in controls) {
printf("The control variable is %s \n", i)
}
}
f(tb2, controls = c("CRT1", "CRT2"))
#The control variable is CRT1
#The control variable is CRT2
Using rlang
f_rlang = function(data, controls){
controls = enquo(controls)
for (i in controls) {
printf("The control variable is %s \n", i)
}
}
f_rlang(db, c(CRT1, CRT2))
#Error in for (i in controls) { : invalid for() loop sequence
CodePudding user response:
I'm not sure if {rlang} itself has a build in functionality to do this, but what you are trying to do mimics the tidy select syntax. So we could use {rlang} together with {tidyselect} to implement this functionality.
This will not only solve your problem, it also adds full tidy select syntax to your function so that we can do f_rlang(db, starts_with("C"))
:
library(rlang)
library(dplyr)
library(R.utils)
db <- tibble(
CRT1 = 15*rnorm(10),
CRT2 = 12*rnorm(10))
f_rlang = function(data, controls){
controls = enexpr(controls)
cols <- tidyselect::eval_select(controls, data)
col_nms <- names(cols)
for (i in col_nms) {
printf("The control variable is %s \n", i)
}
}
f_rlang(db, c(CRT1, CRT2))
#> The control variable is CRT1
#> The control variable is CRT2
f_rlang(db, starts_with("C"))
#> The control variable is CRT1
#> The control variable is CRT2
Created on 2022-09-30 by the reprex package (v2.0.1)