Search code examples
rfunctionarguments

In R, can I pass arguments of the parameter from a variable (only if that variable exists)?


I am creating a shiny app where the user passes some inputs in the app. Based on those inputs, I am trying to pass arguments to the function called 'cohort()'. However, I am encountering issues in passing the arguments to the cohort() function. Here is the relevant portion of my code:

This code loops to create multiple variables based on user inputs.

library(Capr)

for (i in seq(2)){
assign(paste0('ad_cr',i),atLeast(1L, 
query = condition(cs(descendants(i)))))
}

Let's assume that 2 variables were created -> ad_cr1 and ad_cr2.

Function when the no variables were generated:

library(Capr)
cd <- cohort(entry = condition(cs(100)),
         attrition = attrition(),
exit = exit(
  endStrategy = observationExit()
))

I am trying to pass the values of ad_cr1 and ad_cr2 to the cohort() function within the attrition argument. However, I am not sure how to do this. How can I modify my code to achieve this?

Function when the two variables were generated:

cd <- cohort(entry = condition(cs(100)),
         attrition = attrition(
                   'ad_cr1' = withAll(ad_cr1),
                   'ad_cr2' = withAll(ad_cr2)),
exit = exit(
  endStrategy = observationExit()
))

Solution

  • Avoid local variables, by keeping variables together in a list; this list can be passed off to other functions like attrition() ; finally I wrapped it all up in a function you can call.

    library(Capr)
    library(purrr)
    
    cohort_builder <- function(sequence, prefix) {
      assign_names <- paste0(prefix, sequence)
      assignations <- map(
        sequence,
        \(x)atLeast(1L,
          query = condition(cs(descendants(x)))
        )
      ) |> set_names(assign_names)
    
    
      cohort(
        entry = condition(cs(100)),
        attrition = do.call(
          attrition,
          map(assignations, \(x){
            withAll(x)
          })
        ),
        exit = exit(
          endStrategy = observationExit()
        )
      )
    }
    
    my_empty <- cohort_builder(sequence = NULL, prefix = NULL)
    my_2 <- cohort_builder(sequence = seq(2), prefix = "ad_cr")