我创建了一个函数,可以对来自库(MASS)的数据集birthwt执行10倍交叉验证。函数中的代码正在做我想要它做的事情。但是,我想使用函数外部返回的值,但我无法访问函数外部的mean_mrate变量。
我的代码是:
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)
}
}
答案 0 :(得分:0)
如果你这样调用这个函数:
result = tenfold3()
result
变量将等于函数内的mean_mrate
变量。
请注意return
从函数中断,并且只执行循环中的第一次迭代。另外,更像R的样式是将函数中的for循环内容包装起来,并使用lapply
调用函数10次。