Can I loop multiple lines of code and save each output?

Viewed 45

I'm testing the accuracy of linear regression models with training and test data, and I would like to be able to run the code 100 times and save the MAPE output in a table or file so I can have a decent error% for the training model. How do I loop the code from the line of sample_size to the line of MAPE and keep each output?

library('tidyverse')
library("ggplot2")
library("readxl")
library("writexl")
library('dplyr')
library('Rmisc')
library('cowplot')
library('purrr')
library('caTools')
library('MLmetrics')
##2008 Set
Bird<-c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10)
Age<-c(10,17,27,10,17,28,10,17,27,10,17,27,10,17,28,10,17,28,10,17,28,10,17,28,10,17,28,11,18,28)
Wing<-c(39,63,98,34,61,99,34,48,80,30,37,65,35,51,71,40,55,79,34,47,77,36,55,84,35,55,88,36,59,74)
Set08<-data.frame(Bird, Age, Wing) %>% 
  group_by(Bird) 
Set08$Bird<-as.factor((Set08$Bird))
Set08

sample_size = floor(0.7*nrow(Set08))

picked = sample(seq_len(nrow(Set08)),size = sample_size)

Training =Set08[picked,]
Training
Test =Set08[-picked,]
Test

trm<-lm(Age~Wing, data=Training)

predval<-predict(object=trm,
                 newdata=Test)
predval

error<-data.frame(actual=Test$Age, calculated=predval)
error

MAPE(error$actual, error$calculated)

1 Answers

If you want to do it as a loop, this should give you a vector of the 100 results:

results<-list()
for (i in 1:100){
  
sample_size = floor(0.7*nrow(Set08))

picked = sample(seq_len(nrow(Set08)),size = sample_size)

  
Training =Set08[picked,]
Training
Test =Set08[-picked,]
Test

trm<-lm(Age~Wing, data=Training)

predval<-predict(object=trm,
                 newdata=Test)
predval

error<-data.frame(actual=Test$Age, calculated=predval)
error

results[[i]] <- MAPE(error$actual, error$calculated)

}

list_of_results <- unlist(results)
Related