简体   繁体   中英

Error in xy.coords(x, y, xlabel, ylabel, log) while knitting the file

I have everything working when I run the chunks but an error occurs when I decide to knit my .rmd file


########### needed for testing purpose #################

library(tree)
set.seed(77191)


library(ISLR)
library(randomForest)
attach(Carseats)
n=nrow(Carseats)
indices=sample(1:n,n/2,replace=F)
cstrain=Carseats[indices,]
cstest=Carseats[-indices,]

tree.cs <- tree(Sales ~. , data = cstrain)
summary(tree.cs)
plot(tree.cs)
text(tree.cs)
y_hat <-predict(tree.cs, newdata = cstest)
test.mse =mean((y_hat - cstest$Sales)^2)  #Test's MSE
test.mse
######################################################

# 2nd chunk
cv.cs <- cv.tree(tree.cs)
cx =cv.cs$size
cy =cv.cs$dev
mymy <- xy.coords(cx,cy)
plot(mymy, xlab = "size", ylab = "dev",  type = "b")
mini.tree <-which.min(cv.cs$dev)
points(mini.tree,cv.cs$dev[mini.tree], col="green", cex= 2, pch = 20)

2nd chunk Yields : ![在此处输入图片说明


#3rd chunk
#pruning
prune.cs <- prune.tree(tree.cs, best = mini.tree)
plot(prune.cs) # the problematic part

y_hat <- predict(prune.cs, newdata = cstest)

mean((y_hat - cstest$Sales)^2)

The 3rd chunk has to yield something similar to this: 在此处输入图片说明 Not a duplicate of:

'x' is a list, but does not have components 'x' and 'y'

Error in xy.coords(x, y, xlabel, ylabel, log) : 'x' is a list, but does not have components 'x' and 'y'

Did not solve the problem:

Fit a Decision Tree classifier to the data; Error in code

I know about the coordinates plot() needs in order to run but here I am trying to plot a tree. Also, it worked many times before but wouldn't just knit the file.

1st chuck is added in case you want to try it by yourself.

Thank you.

I suppose your problematic line should be

prune.cs <- prune.tree(tree.cs, best = cv.cs$size[mini.tree])

instead of

prune.cs <- prune.tree(tree.cs, best = mini.tree)

You are not interested in the index, which can change every time you do cross-validation, but the tree size at that index.

The same thing is true in the 2nd chunk where you have

points(mini.tree,cv.cs$dev[mini.tree], col="green", cex= 2, pch = 20)

which should be

points(cv.cs$size[mini.tree], cv.cs$dev[mini.tree], col="green", cex= 2, pch = 20)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM