Reputation: 11
Code that works:
scale_this <- function(x){
(x - mean(x, na.rm=TRUE)) / sd(x, na.rm=TRUE)
}
get_the_boxes <- function(df,y,val1,provider_id){
temp <- df %>%
group_by_("MPIN") %>%
# mutate(y = scale_this(y),PAID_DATE_GRP = scale_this(PAID_DATE_GRP))
mutate(y = scale_this(mbr_cnt_log))
return(temp)
}
edit: Want to add how I call the function:
my_data <- get_the_boxes(new2,"mbr_cnt_log",1,"mpin")
However, I want to pass the column name "mbr_cnt_log" via parameter "y". I've seen answers to similar questions (this was a good example), but they have failed for me (user error, no doubt).
Only showing the line with a change, here's what I've tried and the error returned:
change:
mutate(y = scale_this(deparse(substitute(y))))
error:
Error in mutate_impl(.data, dots) :
Evaluation error: non-numeric argument to binary operator.
change:
mutate(y = scale_this(df[[y]]))
error:
Error in mutate_impl(.data, dots) :
Column `y` must be length 24 (the group size) or one, not 0
change:
mutate(y = scale_this(df[,y]))
error:
Error in mutate_impl(.data, dots) :
Evaluation error: Column `"mbr_cnt_log"` not found.
Upvotes: 1
Views: 80
Reputation: 11
Here's what I got t work:
get_the_boxes <- function(df,y,val1,provider_id){
y<-enquo(y)
temp <- df %>%
group_by_("MPIN") %>%
# mutate(y = scale_this(y),PAID_DATE_GRP = scale_this(PAID_DATE_GRP))
mutate(y = scale_this(!!y))
return(temp)
}
my_data <- get_the_boxes(new2,mbr_cnt_log,1,"mpin")
This is essentially what MrFlick wrote, but a bit different. I found this to help.
Upvotes: 0
Reputation: 206586
With the lastest version of dplyr
, you use enquo
and the bang-bang !!
operator to capture and expand symbols into dplyr expressions
get_the_boxes <- function(df, y) {
y <- enquo(y)
df %>%
group_by(hp) %>%
mutate(!!quo_name(y) := scale_this(!!y))
}
get_the_boxes(mtcars, disp)
Upvotes: 2