简体   繁体   English

无法将变量范围限制为R函数中的`standardize :: standardize`

[英]Unable to scope variables into R functions for `standardize::standardize`

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. 我正在尝试创建一个自定义函数,该函数允许我使用standardize包将混合效果标准化应用于大型dplyr数据框。

I have been unsuccessful is parsing function arguments into the standardize function despite having tried various forms of quosure, using !! 尽管尝试了各种形式的quosure,但我仍然无法将函数参数解析为standardize函数!! , lazy evaluation and using do.call . ,懒惰的评估和使用do.call

I have reviewed the information in these threads ( 1 , 2 ) and tried to implement them. 我已经审查了这些线程(信息12 ),并试图实现它们。

# 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 eval(predvars,data,env)中的错误:找不到对象“ x”

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. q_m_efx2(df, x)给出相同的错误。

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? 我要去哪里错了?

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). 语法由rlang包实现,并且仅可用于需要该值的函数(例如“ tidyverse”函数中的函数)。 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. 特别是,当前版本的standardize不支持此语法进行变量扩展。 Therefore you must use the more traditional methods. 因此,您必须使用更传统的方法。

Here's how you can re-write your function using the substitute() function 这是您可以使用substitute()函数重新编写函数的方法

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

quick_mixed_efx(df, x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM