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.