解决自定义函数中的作用域问题以从“htest”对象中提取数据

solving scoping issure in a custom function to extract data from `htest` object

我在尝试提取数据帧时遇到了一些范围界定问题。

这是一个更大的自定义函数的 部分 ,用于从 McNemar 的测试和其他 htest 对象中提取数据:

get_data <- function(x, ...) {
  data_name <- unlist(strsplit(x$data.name, " (and|by) "))
  data_call <- lapply(data_name, str2lang)
  columns <- lapply(data_call, eval)
  as.table(columns[[1]])
}

使用外部函数环境

函数按预期运行:

# data
Performance <-
  matrix(c(794, 86, 150, 570),
    nrow = 2,
    dimnames = list(
      "1st Survey" = c("Approve", "Disapprove"),
      "2nd Survey" = c("Approve", "Disapprove")
    )
  )

# using the function
mod <- stats::mcnemar.test(Performance)
get_data(mod) # it works!

#>             2nd Survey
#> 1st Survey   Approve Disapprove
#>   Approve        794        150
#>   Disapprove      86        570

使用内部函数环境

不幸的是没有用

foo <- function(data) {
  mod <- stats::mcnemar.test(data)
  print(mod) # making sure data is being read internally
  
  get_data(mod) # it doesn't work :(
}

foo(Performance)
#> 
#>  McNemar's Chi-squared test with continuity correction
#> 
#> data:  data
#> McNemar's chi-squared = 16.818, df = 1, p-value = 4.115e-05
#> Error in as.table.default(columns[[1]]): cannot coerce to a table

是否有任何方法可以使此工作生效,通过更改自定义函数以提取数据 (get_data) 或通过修改调用它的函数 (foo)?

正如@RuiBarradas 在评论中提到的,mcnemar.test 正在创建 list 元素 'data.name' 作为输入 data 而不是存储在其中的值。应用测试后可以更改

get_data <- function(x, ...) {
   data_name <- unlist(strsplit(x$data.name, " (and|by) "))
   data_call <- lapply(data_name, str2lang)
   columns <- lapply(data_call, eval)
   as.table(columns[[1]])
   
   
 }
 
 
foo <- function(data) {
   
   mod <- stats::mcnemar.test(data)
   mod$data.name <- deparse(substitute(data))
   print(mod) # making sure data is being read internally
  
   get_data(mod) # it doesn't work :(
 }

foo(Performance)
#   McNemar's Chi-squared test with continuity correction

#data:  Performance
#McNemar's chi-squared = 16.818, df = 1, p-value = 4.115e-05

#            2nd Survey
#1st Survey   Approve Disapprove
#  Approve        794        150
#  Disapprove      86        570

或使用get

get_data <- function(x, ...) { 
    data_name <- unlist(strsplit(x$data.name, " (and|by) "))
    as.table(get(data_name, envir = parent.frame()))
    }
foo(Performance)
#McNemar's Chi-squared test with continuity correction

#data:  Performance
#McNemar's chi-squared = 16.818, df = 1, p-value = 4.115e-05

#            2nd Survey
#1st Survey   Approve Disapprove
#  Approve        794        150
#  Disapprove      86        570