1

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.
Frank
  • 66,179
  • 8
  • 96
  • 180
  • You'll probably need to do something like `!!rlang::sym(y)`. There's a whole new system for doing this stuff in dplyr that you're going to have to google, read about and learn. – joran Feb 21 '18 at 21:09
  • you can try to go around if nothing else come up, temp$y <- temp[,y] #where y is name of column #scaling temp[,y] <- temp$y #rewrite the initial column – jyr Feb 21 '18 at 21:17

2 Answers2

2

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)
MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

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.