0

I am trying to create a custom function that allows me to apply mixed effects standardization to a large dplyr data frame using the standardize package.

I have been unsuccessful is parsing function arguments into the standardize function despite having tried various forms of quosure, using !!, lazy evaluation and using do.call.

I have reviewed the information in these threads (1, 2) and tried to implement them.

# example_df

df <- data.frame(
subject = rep( c("01", "02", "03", "04", "05"), 1, each = 5),
time = rep(1:5, 5),
x = rnorm(25, 0, 1) )
library(dplyr)
df <- tbl_df(df) %>% mutate(subject = factor(subject))

library(standardize)

quick_mixed_efx <- function(df, col){
st_x <- standardize(!!col ~ time + 1| subject, data = df)}

quick_mixed_efx(df, x)

Error in eval(predvars, data, env) : object 'x' not found

Another (failed) attempt:

q_m_efx_2 <- function(df, col){
s_form <- !! col ~ time + 1 | subject
st_x <- do.call("standardize", list(formula = s_form, data = df))
return(st_x) }

q_m_efx2(df, x) gives the same error.

Ideally, I would like to be able to extract, directly, the standardized data from the function as per:

st_x <- standardize(x ~ time + 1|subject, data = df)

st_x$data$x

Which works fine outside of a function

Where am I going wrong?

romsdocs
  • 68
  • 6

1 Answers1

1

The !! syntax is implemented by the rlang package and is only available for use in functions that are expecting such a value (such as the functions in "tidyverse" pacakages). It is not a general purpose way to deal with non-standard evaluation. In particular, the current version of the standardize does not support this syntax for variable expansion. Therefore you must use the more traditional methods.

Here's how you can re-write your function using the substitute() function

quick_mixed_efx <- function(df, col) {
  form <- substitute(col ~ time + 1| subject)
  standardize(form, data = df)}

quick_mixed_efx(df, x)
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thank you @MrFlick that works, however I cannot build in `substitute()` to extract the data from the function. e.g.
    `quick_mixed_efx <- function(df, col) { form <- substitute(col ~ time + 1| subject) res <- standardize(form, data =df) output <- substitute(res$data$col) return(output) }`
    `a1 <- quick_mixed_efx(df,x) str(a1)`
    > language structure(list(call = standardize(formula = form, data = df), scale = 1, formula = x ~ time + 1 | subject, family = structure(list(
    – romsdocs Aug 13 '18 at 23:19
  • to extract the elements from the standardized object from within the function this worked: `quick_mixed_efx <- function(df, col) { form <- substitute(col ~ time + 1| subject); st_x <- standardize(form, data = df); output <= st_x$data[, as.character (substitute(col) ) ) [,1] ; return (output)}` – romsdocs Aug 14 '18 at 09:24