R - Pass variable to a function

96 Views Asked by At

In R, I am running a for loop and in each loop I create a variable (var) by referring to the value in a column in a dataframe (dataframe is called temp). I then want to pass this variable (var) as one of the inputs to a function (called gini_scorecard).

The obvious error I am getting is Error: Column `var` is unknown

Below is the code I am using: (below that is the structure of the gini_scorecard function)

for(i in 1:nrow(temp)) {
  
  var = as.character(temp[i,1])

  temp200 <- data_var %>%
    # mutate(col_var = !! var2) %>%
    select(application_number, target_model_defn, target_trad_defn, current_eligible, main_applicants, registration_quarter, 
           registration_month, registration_year, months_on_book, dev_period, contains(var))
  
  gini_dev = gini_scorecard(temp200 %>% filter(dev_period == 1), var, target_trad_defn, 1)

}

Gini scorecard function structure (first few lines of function) - the problem variable is the second variable (model) - this variable is telling the function to look at a specific column within the passed dataframe (dset). I have a feeling it has something to do with quoting but I have been unable to solve the problem. Any ideas would be greatly appreciated. (ideally I do not want to change the function).


gini_scorecard <- function(dset, model, target, target_value) {
  
  # quote variables so that dplyr function will work
  group_var <- enquo(model)
  target <- enquo(target)
  by <- quo_name(group_var)  
  
  # need to ensure all possible values of the modelled variables are stored
  all <- dset %>%
    group_by(!! group_var) %>%
    mutate(total = n()) %>%
    select(!! group_var, total) %>%
    distinct() %>%
    arrange(!! group_var)
  
0

There are 0 best solutions below