O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

In this recipe, we show you basic code to perform k-fold cross-validation for linear regression. You can adapt the same code structure for all other regression methods. Although some packages such as caret, DAAG, and boot provide cross-validation functionality out of the box, they cover only a few machine learning techniques. You might find a generic framework to be useful and be able to adapt it to whatever machine learning technique you might want to apply it to. To do this, follow these steps:

  1. Read the data:
> bh <- read.csv("BostonHousing.csv") 
  1. Create the two functions shown as follows; we show line numbers for discussion:
1 rdacb.kfold.crossval.reg <- function(df, nfolds) { 2 fold <- sample(1:nfolds, nrow(df), replace ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required