gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:20:09 25 4
gpt4 key购买 nike

我在尝试提取数据框时遇到了一些范围界定问题。
这是一个 部分 使用更大的自定义函数从 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

关于r - 解决自定义函数中的作用域问题以从 `htest` 对象中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65533301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com