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)
#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'
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.