Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
train linear regression in R using kfold method
## R version 3.6.1
## Created by DataRockie 15 November 2019
## load library
library(caret)
library(mlbench)
library(dplyr)
## load dataset
data("BostonHousing")
## tibble dataframe
BostonHousing <- as.tbl(BostonHousing)
## create folds
(folds <- createFolds(BostonHousing$medv, k=5, list=T))
## train linear regression
kfoldLM <- function(data, k) {
folds <- createFolds(BostonHousing$medv, k=k, list=T)
result <- vector()
for(fold in folds) {
trainData <- data[-fold, ]
testData <- data[fold, ]
r2 <- summary(lm(trainData))$r.squared
result <- append(result, r2)
}
cat("Average R2:", round(mean(result),4) )
cat("\nStandard Deviation R2:", round(sd(result),4) )
}
## test function with k=5
kfoldLM(data = BostonHousing, k = 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment