gpt4 book ai didi

r - is.data.frame(data) object ...在函数上下文中找不到

转载 作者:行者123 更新时间:2023-12-04 10:35:34 24 4
gpt4 key购买 nike

使用包 tree 时遇到一个奇怪的问题cv.tree来自 R 中用户定义函数的函数:

func <- function(train) {
classification.tree <- tree(log10(perf) ~ syct+mmin+mmax+cach+chmin+chmax, train, split = "gini")
cv.tree(classification.tree, ,FUN=prune.tree, K = 4)
return (classification.tree)
}
data(cpus, package="MASS")
result <- func(cpus)
plot(result)

这会产生错误:
Error in is.data.frame(data) : object 'train' not found 
16 is.data.frame(data)
15 model.frame.default(formula = log10(perf) ~ syct + mmin + mmax +
cach + chmin + chmax, data = train, subset = c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", ...
14 eval(expr, envir, enclos)
13 eval(expr, p)
12 eval.parent(m)
11 tree(formula = log10(perf) ~ syct + mmin + mmax + cach + chmin +
chmax, data = train, split = "gini", subset = c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", ...
10 eval(expr, envir, enclos)
9 eval(oc)
8 model.frame.tree(object)
7 model.frame(object)
6 cv.tree(classification.tree, , FUN = prune.tree, K = 4) at .active-rstudio-document#4
5 func(cpus) at .active-rstudio-document#9
4 eval(expr, envir, enclos)
3 eval(ei, envir)
2 withVisible(eval(ei, envir))
1 source("~/.active-rstudio-document", echo = TRUE)

同时,如果我直接从脚本中调用相同的代码,它就可以正常工作:
data(cpus, package="MASS")
classification.tree <- tree(log10(perf) ~ syct+mmin+mmax+cach+chmin+chmax, cpus, split = "gini")
cv.tree(classification.tree, ,FUN=prune.tree, K = 4)
plot(classification.tree)

我错过了什么?

最佳答案

崩溃发生在 cv.tree()称呼。
更新:cv.tree电话model.frame ,在这个函数里面有一个 eval ,但变量 train不存在于该函数的环境中。

我会继续挖掘......如果我深入 Debug模式 model.frame并更改 data列出从 'train' 到 'cpus' 的 'object' 元素,然后是 eval找到对象并执行。

安恩德:我回到了我开始的地方。这是一个环境和懒惰评估问题。
修复方法是使用 force :

func <- function(train) {
force(train)
classification.tree <- tree(log10(perf) ~ syct+mmin+mmax+cach+chmin+chmax, train, split = "gini")
cv.tree(classification.tree, FUN=prune.tree, K = 4)
return (classification.tree)
}

这使得“火车”存在于 cv.tree 可用的环境中。以及它调用的函数。环境会变得很奇怪:-);这是其中一个例子。

关于r - is.data.frame(data) object ...在函数上下文中找不到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28148533/

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