0
我已經創建了一個函數來執行從庫(MASS)的數據集birthwt 10交叉驗證。函數內的代碼正在做我想做的事情。但是,我想使用函數外返回的值,但我不能訪問函數外的mean_mrate變量。10倍交叉驗證 - 功能問題
我的代碼是:
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 the dataframe birthwt
tester = df_i[1:fold_2,] # remove first tenth of rows - USE PREDICT ON THIS DATA
trainer = df_i[-c(1:fold_2),] # all other than the first tenth of rows - USE GLM ON THIS DATA
#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)
}
}
我是一個新的R用戶。您能否展開/向我展示示例代碼以瞭解如何執行此操作? – miyagi 2014-11-14 17:53:56