Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 10倍交叉验证-功能问题_R_Function_Cross Validation - Fatal编程技术网

R 10倍交叉验证-功能问题

R 10倍交叉验证-功能问题,r,function,cross-validation,R,Function,Cross Validation,我创建了一个函数,用于对来自库(MASS)的数据集执行10倍交叉验证。函数中的代码正在执行我希望它执行的操作。但是,我想使用函数外部返回的值,但无法访问函数外部的平均值变量 我的代码是: library(MASS) tenfold3 = function() { fold = 10 end = nrow(birthwt) fold_2 = floor(end/fold) misclasrate=numeric() for(i in 1:10){ df_i =

我创建了一个函数,用于对来自库(MASS)的数据集执行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)

  }

}

如果您这样调用函数:

result = tenfold3()
结果
变量将等于函数内的
平均值
变量


请注意,
return
中断函数,只执行循环中的第一次迭代。此外,更类似于R的样式是将for循环中的内容包装在一个函数中,并使用
lappy
调用该函数10次

我是一个新的R用户。您能为我扩展/展示如何实现这一点的示例代码吗?