r - 10 fold Cross Validation - function issues -



r - 10 fold Cross Validation - function issues -

i have created function perform 10 fold cross validation on info set birthwt library(mass). code within function doing want do. however, want utilize values returned outside of function cant access mean_mrate variable outside of function.

my code is:

library(mass) tenfold3 = function() { fold = 10 end = nrow(birthwt) fold_2 = floor(end/fold) misclasrate=numeric() for(i in 1:10){ df_i = birthwt[sample(nrow(birthwt)),] # random sort dataframe birthwt tester = df_i[1:fold_2,] # remove first 10th of rows - utilize predict on info trainer = df_i[-c(1:fold_2),] # other first 10th of rows - utilize glm on info #mod = glm(low~age,family=binomial,data=trainer) mod = glm(low~age+lwt+race+smoke+ptl+ht+ui+ftv,family=binomial,data=trainer) ypred = predict(mod,data=tester,type='response') ypred = trunc(0.5+predict(mod,data=tester,type='response')) # predicted values val_df = data.frame(trainer[,1],ypred) names(val_df) = c('train','ypred') val_df$misclas = (val_df$train == val_df$ypred) misclasrate[i] = 1-sum(val_df$misclas) / nrow(val_df) mean_mrate = signif(mean(misclasrate),4) g = cbind(misclasrate[i],mean_mrate) return(mean_mrate) } }

if phone call function this:

result = tenfold3()

the result variable equal mean_mrate variable within function.

note return breaks function , first iteration in loop executed. in addition, more r-like style wrap contents within loop in function, , phone call function 10 times using lapply.

r function cross-validation

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -