1
votes

New to using the TidyVerse family in R. Was attempting to use mutate within a function to classify the rows of a variable as either positive or negative. Works fine outside of my function call, but strictly returns zero within it.

Able to get the function working as intended when I do not use mutate, but I would like to understand the issues I am running into. I can tell that the issue is that I am passing in a string for the function. I have messed around with various things like as.name(),quo(), and UQ, but I have not really achieved success. Don't really understand how to best use the Dplyr verbs within a function - Should I just revert to more normal syntax?

find_if_maj <- function(var_name,curr_year,k_i) {

  if(var_name == "unemp_chg") {
    temp <- agg_econ %>% select(year,var_name) %>% # Subsetting to the desired variable
      filter((year <= curr_year) & (year >= (curr_year - k_i))) %>% # Subsetting to the desired range of years
      mutate(indicator = ifelse(var_name <= 0, 1, 0)) # Creating a dummy indicator based on if the value is negative or positive
    return(temp) # Just returning the tibble for bug checking

  }

}

find_if_maj("unemp_chg",1970,5) %>% mutate(outsidefunc = ifelse(unemp_chg <= 0, 1, 0)) # Running the function, displaying what result should be


I expect the indicator column created by mutate to be filled with 1's and 0's depending on the value input. The indicator column created by the function just returns 0's regardless of the input value, but the outside_func column that I generated to check properly returns the correct values.

1
Hi @Ariel Polani welcome to SO. It´s important for us to help you some data is provided to allow us to reproduce the behaviour informed. About your question, as we dont have data yet, I suggest you to take a look on dplyr function named case_when (dplyr.tidyverse.org/reference/case_when.html). case_when is way simpler than if else and cover a bigger range of possibilities - Adelmo Filho
Thanks for the advice. Using clintwood's !!sym seems to have done for the trick for me. I'll make sure to include some data on future questions. - Ariel Polani

1 Answers

1
votes

Inside your function var_name is a string but you want it to be a reference to your column name. Try this

find_if_maj <- function(var_name,curr_year,k_i) {

  if(var_name == "unemp_chg") {
    temp <- agg_econ %>% select(year,var_name) %>% # Subsetting to the desired variable
      filter((year <= curr_year) & (year >= (curr_year - k_i))) %>% # Subsetting to the desired range of years
      mutate(indicator = ifelse(!!sym(var_name) <= 0, 1, 0)) # Creating a dummy indicator based on if the value is negative or positive
    return(temp) # Just returning the tibble for bug checking

  }
}