currently I am running into some problems with Non-Standard Evaluation when trying to wrap a function around some calculations done with dplyr und purrr that I use on multiple occasions.
I have read about NSE and also think I know the point where my function does not work properly - however, I could not figure out why this is.
Examplarily, I want to wrap a function around the following calculations, where the grouping variable as well as the name of the new variable, the utilized categorization variable and the input variable for the mean should be dynamic:
Data <- Data %>%
group_by(WeekBeforeRelease) %>%
mutate(visitors_genreother_instr = map_dbl(Genre_Category, ~ mean(Visitors[Genre_Category != .x]))) %>%
ungroup() %>%
as.data.frame()
Which turns this function into the following, using NSE as described here:
Function_Other <- function(ENDOGVAR, VARNAME, GROUP_MOVIE, GROUP_TIME){
ENDOGVAR <- enquo(ENDOGVAR)
VARNAME <- quo_name(enquo(VARNAME))
GROUP_MOVIE <- enquo(GROUP_MOVIE)
GROUP_TIME <- enquo(GROUP_TIME)
Data <<- Data %>%
group_by(!!GROUP_TIME) %>%
mutate(!!VARNAME := map_dbl(!!GROUP_MOVIE, ~mean(!!ENDOGVAR[!!GROUP_MOVIE != .x]))) %>%
ungroup() %>%
as.data.frame()
}
However, this does not seem to handle the subsetting with brackets in the mean calculation well. If I subtitute the !!ENDOGVAR with Visitors, everything works fine and as intended. However, as is, it produces the following error:
Error in NextMethod("[") : object '.x' not found
I am happy about any help that points me towards understanding this problem.
Thanks a lot in advance!
rondo