dimanche 31 janvier 2021

R: Saving the Results of a Loop

I am using the R programming language. I am learning about loops and how to store the results of a loop. For instance, I wrote the following code that loops a function (generates random data and fits different decision trees):

#load libraries    
    library(caret)
library(rpart)

#generate data

a = rnorm(1000, 10, 10)

b = rnorm(1000, 10, 5)

c = rnorm(1000, 5, 10)

group <- sample( LETTERS[1:2], 1000, replace=TRUE, prob=c(0.5,0.5) )
group_1 <- 1:1000

#put data into a frame
d = data.frame(a,b,c, group, group_1)

d$group = as.factor(d$group)

#place results in table
#final_table = matrix(1, nrow = 10, ncol=10)


e <- d



vec1 <- sample(200:300, 5)
vec2 <- sample(400:500,5)
vec3 <- sample(700:800,5)

for (i in seq_along(vec1)) { 
    for (j in seq_along(vec2)) {
        for (k in seq_along(vec3)) {
            # d <- e
            d$group_2 = as.integer(ifelse(d$group_1 < vec1[i] , 0, ifelse(d$group_1 >vec1[i]  & d$group_1 < vec2[j] , 1, ifelse(d$group_1 >vec2[j]  & d$group_1 < vec3[k] , 2,3))))
            
            
            
            
            d$group_2 = as.factor(d$group_2)
            
            fitControl <- trainControl(## 10-fold CV
                method = "repeatedcv",
                number = 2,
                ## repeated ten times
                repeats = 1)
            
            TreeFit <- train(group_2 ~ ., data = d[,-5],
                             method = "rpart",
                             trControl = fitControl)
            
            pred <- predict(
                TreeFit,
                d[,-5])
            
            con <- confusionMatrix(
                d$group_2,
                pred) 
            
            #update results into table
            #final_table[i,j] = con$overall[1]
            acc=c(vec1[i],vec2[j],vec3[k],con$overall[1])
            print(acc)
            
            
        }
    }
}

I am interested in saving the results of "acc" into a table (or a data frame). I am able to print all values of "acc", but when I formally view the results of "acc" : only the last line is displayed.

My question: is it possible to take the entire printed output (i.e. "acc") and store it into a table?

Thanks




Aucun commentaire:

Enregistrer un commentaire