Question: I got the error: Error in yall [ test ] : invalid subscript type 'list' Traceback: 1 . mean ( ( kmod$fitted - yall [

I got the error:
Error in yall[test]: invalid subscript type 'list'
Traceback:
1. mean((kmod$fitted - yall[test])^2
Below is my code:
## import libraries needed
library(testthat)
library(digest)
library(stringr)
library(MASS)
library(kknn)
n = nrow(Boston) #number of observatons/rows, i.e. sample size
xall = Boston$dis #our input variable
yall =10*Boston$nox #our output variable
# create data frame df that consists only of our input and output variables
df = data.frame(xall,yall) #simple data frame for convenience
dim(df) #checking the dimension of the dataframe df (note there are 506 obs)
set.seed(123)
tr = sample(x=1:506, size=400, replace=FALSE)
head(tr)
# Create train and test data frames
train <- df[tr,]
test <- df[-tr,]
#loop over values of k, fit on train, predict on test
kvec =1:350
nk=length(kvec)
outRMSE = rep(0,nk) #pre-allocating RMSE for out-of-sample data
inRMSE = rep(0,nk) #pre-allocating RMSE for in-sample data
# Loop over the values of k
for (i in kvec){
# Fit the kknn model using the training dataset
kmod = kknn(yall ~ xall, train=train, test=test, k=123, kernel="rectangular")
kmodtr = kknn(yall ~ xall, train=train, test=train, k=123, kernel="rectangular")
# Compute the out-of-sample and in-sample RMSEs
outRMSE[i]<- sqrt(mean((kmod$fitted - yall[test])^2))
inRMSE[i]<- sqrt(mean((kmodtr$.fitted - yall[train])^2))
}
# Print the first few values of the out-of-sample and in-sample RMSEs
print(outRMSE)
print(inRMSE)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!