r - Saving Table Counts as a Vector -


i trying loop through sequence of values , save table count results in separate vector or matrix. i'm new programming please excuse poor attempt.

here problem:

pred_test <- seq(0, 1, length=1000) test$purchaser_flag <- sample(c(0,1), size=1000, replace= true) crit = seq(from=0, to=1, by=.01)  list <- matrix(0, nrow=101, ncol=2)  (i in 1:length(crit)) { list[i,] <- as.numeric(table(pred_test >= i, test$purchaser_flag)[2,])  } 

i want loop through values of crit , save results of each associated table count row in new vector called 'list'. pred_test probability score 0-1 , purchaser flag associated class of 0 or 1. want save these counts each associated critical thresholds in crit.

please let me know if there easier way this.

use sapply , ensure dimensions of tables generate same (2 x 2) in case:

library(dplyr) library(tidyr)   # generate data df_foo = data_frame(   pred_test = runif(1000),   purchaser_flag = sample(c(0, 1), size = 1000, replace = true) )  # collect confusion matrices  m_confusion = sapply(   seq(0, 1, .1), function(x) {      # straighten out matrix     as.numeric(       # create confusion matrix       table(         # ensure levels represented         factor(           df_foo$pred_test > x, levels = c("true", "false")         ),          df_foo$purchaser_flag       )     )   } )  # add dimnames matrix created colnames(m_confusion) = seq(0, 1, 0.1)  # create rownames dummy object rownames_confusion =    unite(     expand.grid(       dimnames(         table(           factor(             df_foo$pred_test > 0.1, levels = c("true", "false")), df_foo$purchaser_flag         )       )     ), rownames, everything()   )$rownames  # attach rownames rownames(m_confusion) = rownames_confusion  # print final object m_confusion 

this gives:

> m_confusion           0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9   1 true_0  510 467 425 376 318 274 210 157 103  52   0 false_0   0  43  85 134 192 236 300 353 407 458 510 true_1  490 428 374 326 284 246 205 158 111  54   0 false_1   0  62 116 164 206 244 285 332 379 436 490 

i sure there easier way create row dimnames, leave figure out.


Comments

Popular posts from this blog

loops - Spock: How to use test data with @Stepwise -

amazon web services - S3 Pre-signed POST validate file type? -