Saving object results from R functions into csv

by GISnew   Last Updated October 10, 2019 17:22 PM

I have this function used for modeling.

 ensemble <- function (x, y, wl=NA) {

  if (is.na (wl[1]) | length (wl)!=ncol (x))
    wl <- 1:ncol (x)

  library (e1071)
  library (randomForest)
  library (pls)

  dat <- data.frame (cbind (y, x)) 
  colnames (dat)[1] <- "y"
  pls <- plsr (y~., data=dat, jackknife=TRUE, scale=T, validation="CV")

  rmse <- RMSEP (pls, "all") 
  rms <- rmse$val[1:2, , -1][,1:25]
  barplot (rms[2,], space=0, col=4, ylim=c (0, max (rms[2,])), las=2, 
           cex.names=0.6, xlab="# latent vectors", ylab="RMSE")
  barplot (rms[1,], space=0, col=2, add=T, axes=F, axisnames=F)
  legend ("topright", legend=c ("cal", "val"), pch=15, col=c (2, 4), bty="n",  
          horiz=T)
  nlv <- as.numeric (readline ("Select # latent vectors for PLSR:"))
  plscf <- as.vector (coef (pls, ncomp=nlv, intercept=F)) ## extract coeff.
  plscf <- plscf / sd (plscf) 
  plsrsq <- R2 (pls, "CV")$val[1, , -1][nlv] 

  rf <- randomForest (x, y, importance=T)
  rfrsq <- rf$rsq[500] 
  rfcf <- rf$importance[,1] 
  rfcf <- as.vector (rfcf / sd (rfcf)) 

  ccoef <- 2^seq (-5, 15, 2) 
  gcoef <- 2^seq (-15, 3, 2) 
  gsfit <- matrix (0, 11, 10) 
  for (i in 1:11){
    for (j in 1:10){
      svmrun <- svm (x, y, type="eps-regression", cross=10, gamma=gcoef[j], 
                     cost=ccoef[i])
      gsfit[i, j]<-svmrun$scorrcoef

    }} ## run for all possible combinations

  svm.param <- which (gsfit==max (gsfit), arr.ind=TRUE)[1,] ## identify best 
  svr <- svm (x, y, type="eps-regression", cross=10, gamma=gcoef[svm.param[2]], 
              cost=ccoef[svm.param[1]]) 
  svr.alpha <- t (svr$coefs) 
  svr.index <- svr$index 

  ## calculate pseudo-regression coefficients from the alpha vector
  svrcf <- numeric (ncol (x))
  for(i in 1:ncol(x)) 
    svrcf[i] <- svr.alpha %*% x[svr.index, i]
  svrcf <- svrcf / sd (svrcf) 
  svrrsq <- svr$scorrcoef 

  ## ensemble from all models and identify important variables

  ensemblecf <- abs (plscf) * plsrsq + abs (svrcf) * svrrsq + abs (rfcf) * rfrsq
  th <- mean (ensemblecf) + sd (ensemblecf) 
  selbands <- ensemblecf > th 

  ## output

  cf <- rbind (wl, plscf, rfcf, svrcf, ensemblecf, selbands)
  colnames (cf) <- colnames (x)

  fit <- c (plsrsq, rfrsq, svrrsq)
  names (fit) <- c ("PLS R2", "RF R2", "SVR R2")
  output <- list (cf, fit, th, pls, rf, svr)
  names (output) <- c ("selection", "fits", "threshold", "PLS", "RF", "SVM")
  class (output) <- "ensemble"
  output
} 

How do I use the objects resulting from the function so that (1) I could to save them into csv files and (2) I would know the important variables/predictors from each of the three models plus the ensemble?

Tags : r modelling


Related Questions


Updated April 17, 2018 03:22 AM

Updated July 27, 2018 03:22 AM

Updated November 30, 2018 07:22 AM

Updated January 08, 2019 10:22 AM