Learn R Programming

caret (version 6.0-94)

knnreg: k-Nearest Neighbour Regression

Description

$k$-nearest neighbour regression that can return the average value for the neighbours.

Usage

knnreg(x, ...)

# S3 method for default knnreg(x, ...)

# S3 method for formula knnreg(formula, data, subset, na.action, k = 5, ...)

# S3 method for matrix knnreg(x, y, k = 5, ...)

# S3 method for data.frame knnreg(x, y, k = 5, ...)

# S3 method for knnreg print(x, ...)

knnregTrain(train, test, y, k = 5, use.all = TRUE)

Value

An object of class knnreg. See predict.knnreg.

Arguments

x

a matrix or data frame of training set predictors.

...

additional parameters to pass to knnregTrain.

formula

a formula of the form lhs ~ rhs where lhs is the response variable and rhs a set of predictors.

data

optional data frame containing the variables in the model formula.

subset

optional vector specifying a subset of observations to be used.

na.action

function which indicates what should happen when the data contain NAs.

k

number of neighbours considered.

y

a numeric vector of outcomes.

train

matrix or data frame of training set cases.

test

matrix or data frame of test set cases. A vector will be interpreted as a row vector for a single case.

use.all

controls handling of ties. If true, all distances equal to the kth largest are included. If false, a random selection of distances equal to the kth is chosen to use exactly k neighbours.

Author

knn by W. N. Venables and B. D. Ripley and ipredknn by Torsten.Hothorn <Torsten.Hothorn@rzmail.uni-erlangen.de>, modifications by Max Kuhn and Chris Keefer

Details

knnreg is similar to ipredknn and knnregTrain is a modification of knn. The underlying C code from the class package has been modified to return average outcome.

Examples

Run this code

data(BloodBrain)

inTrain <- createDataPartition(logBBB, p = .8)[[1]]

trainX <- bbbDescr[inTrain,]
trainY <- logBBB[inTrain]

testX <- bbbDescr[-inTrain,]
testY <- logBBB[-inTrain]

fit <- knnreg(trainX, trainY, k = 3)

plot(testY, predict(fit, testX))

Run the code above in your browser using DataLab