szcf-weiya / techNotes

My notes about tech (Linux/R/Julia/Python/Cpp/etc.)
https://tech.hohoweiya.xyz/
11 stars 7 forks source link

Error in eval(predvars, data, env) #10

Open szcf-weiya opened 3 years ago

szcf-weiya commented 3 years ago
$ Rscript Ex.9.5.R
Error in eval(predvars, data, env) : object 'y' not found
Calls: calc_df ... eval -> eval -> model.frame.default -> eval -> eval
Execution halted

the error is caused by predict, try predict.tree

$ Rscript Ex.9.5.R
Error in predict.tree(treefit) : could not find function "predict.tree"
Calls: calc_df
Execution halted

with print(treefit$terms),

$ Rscript Ex.9.5.R
y[, i] ~ x
attr(,"variables")
list(y[, i], x)
attr(,"factors")

       x
y[, i] 0
x      1
attr(,"term.labels")
[1] "x"
attr(,"order")
[1] 1
attr(,"intercept")
[1] 1
attr(,"response")
[1] 1
attr(,".Environment")
<environment: 0x2d22e88>
attr(,"predvars")
list(y[, i], x)
attr(,"dataClasses")
      y[, i]            x
   "numeric" "nmatrix.10"

but with print(model.frame(treefit)), it throws the same error as predict,

Error in eval(predvars, data, env) : object 'y' not found
Calls: calc_df ... eval -> eval -> model.frame.default -> eval -> eval
Execution halted

the source code of model.frame.default can be shown by typing the name.

szcf-weiya commented 3 years ago
xy = as.data.frame(cbind(y[,i], x))
colnames(xy) = c("y", paste0("x", 1:p))
treefit = tree(y ~ ., xy)
print(treefit$terms)
print(model.frame(treefit))
$ Rscript Ex.9.5.R
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10

attr(,"variables")
list(y, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10)
attr(,"factors")
    x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
y    0  0  0  0  0  0  0  0  0   0
x1   1  0  0  0  0  0  0  0  0   0
x2   0  1  0  0  0  0  0  0  0   0
x3   0  0  1  0  0  0  0  0  0   0
x4   0  0  0  1  0  0  0  0  0   0
x5   0  0  0  0  1  0  0  0  0   0
x6   0  0  0  0  0  1  0  0  0   0
x7   0  0  0  0  0  0  1  0  0   0
x8   0  0  0  0  0  0  0  1  0   0
x9   0  0  0  0  0  0  0  0  1   0
x10  0  0  0  0  0  0  0  0  0   1
attr(,"term.labels")
 [1] "x1"  "x2"  "x3"  "x4"  "x5"  "x6"  "x7"  "x8"  "x9"  "x10"
attr(,"order")
 [1] 1 1 1 1 1 1 1 1 1 1
attr(,"intercept")
[1] 1
attr(,"response")
[1] 1
attr(,".Environment")
<environment: 0x2fb61a0>
attr(,"predvars")
list(y, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10)
attr(,"dataClasses")
        y        x1        x2        x3        x4        x5        x6        x7
"numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric"
       x8        x9       x10
"numeric" "numeric" "numeric"
Error in is.data.frame(data) : object 'xy' not found
Calls: calc_df ... eval -> eval -> model.frame.default -> is.data.frame
Execution halted

this would be caused by image

szcf-weiya commented 3 years ago

reproduce the same error in a MWE, and propose it on https://stackoverflow.com/questions/66686452/predict-tree-function-throws-evalpredvars-data-env-object-y-not-found