在环境中检查数据的功能-R

时间:2019-02-22 11:02:59

标签: r

我在环境问题中知道这一点,但我需要帮助找出我要去哪里。

我需要检查编织环境(Rmd)中是否存在数据。我想编写一个可以在其他函数中使用的函数:

## Function to check x exists in some environment
data_check_fun <- function(x, e = parent.frame()) {

  ## Use substitute so I can pass in unquoted variable
  df_name <- deparse(substitute(x))

  ## Check env looking in
  print("looking in env: ")
  print(e)

  exists(df_name, envir = e)
}

## Create df in Global env
df <- data.frame()

## Try function (works)
> data_check_fun(x = df)
[1] "looking in env: "
<environment: R_GlobalEnv>
[1] TRUE
> data_check_fun(x = not_df)
[1] "looking in env: "
<environment: R_GlobalEnv>
[1] FALSE

## Create new env: knit_env
knit_env <- new.env()

## Put df in knit_env
knit_env$knit_df <- data.frame()

## Check df is in knit_env
> ls(knit_env)
[1] "knit_df"

## Try function (works)
> data_check_fun(x = knit_df, e = knit_env)
[1] "looking in env: "
<environment: 0xda4ac60>
[1] TRUE
> data_check_fun(x = not_df, e = knit_env)
[1] "looking in env: "
<environment: 0xda4ac60>
[1] FALSE

## Create new function e.g. to plot, which calls data_check fun
plot_function <- function(plot_data, env) {
  data_check_fun(x = plot_data, e = env)
}

## Pass data from knit_env into plot function (does not work)
> plot_function(plot_data = knit_df, env = knit_env)
[1] "looking in env: "
<environment: 0xda4ac60>
[1] FALSE

我认为是因为data_check_fun内的plot_function正在寻找现在不存在的plot_data。有没有办法我可以做到这一点。理想情况下,我不想引用传递给plot_function的参数。

1 个答案:

答案 0 :(得分:3)

如果将data_check_fun的第一个参数简单地定义为字符串,会容易得多。如问题中那样,使用非标准评估通常需要付出大量额外的努力,但是如果您确实想在不显式引用参数的情况下进行评估,则可以捕获该调用,建立新的调用并自己进行评估,如下所示:

plot_function2 <- function(plot_data, env) {
  mf <- match.call()
  m <- match(c("plot_data", "env"), names(mf), 0L)
  mf <- mf[c(1L, m)]
  names(mf)[m] <- c("x", "e")[m > 0]
  mf[[1L]] <- quote(data_check_fun)
  eval.parent(mf)
}

# test
plot_function2(plot_data = knit_df, env = knit_env)  

另请参见lm的源代码。