R/getTree.R

Defines functions getTree

Documented in getTree

getTree <- function(rfobj, k=1, labelVar=FALSE) {
  if (is.null(rfobj$forest)) {
    stop("No forest component in ", deparse(substitute(rfobj)))
  }
  if (k > rfobj$ntree) {
    stop("There are fewer than ", k, "trees in the forest")
  }
  if (rfobj$type == "regression") {
      tree <- cbind(rfobj$forest$leftDaughter[,k],
                    rfobj$forest$rightDaughter[,k],
                    rfobj$forest$bestvar[,k],
                    rfobj$forest$xbestsplit[,k],
                    rfobj$forest$nodestatus[,k],
                    rfobj$forest$nodepred[,k],
                    rfobj$forest$nodeSS[,k],
                    rfobj$forest$nodeImprove[,k])[1:rfobj$forest$ndbigtree[k],,drop=F]
      dimnames(tree) <- list(1:nrow(tree), c("left daughter", "right daughter",
                                         "split var", "split point", "status",
                                         "prediction", "SS", "improve"))
  } else {
      tree <- cbind(rfobj$forest$treemap[,,k],
                    rfobj$forest$rightDaughter[,k],
                    rfobj$forest$bestvar[,k],
                    rfobj$forest$xbestsplit[,k],
                    rfobj$forest$nodestatus[,k],
                    rfobj$forest$nodepred[,k],
                    rfobj$forest$nodeImprove[,k])[1:rfobj$forest$ndbigtree[k],,drop=F]
      dimnames(tree) <- list(1:nrow(tree), c("left daughter", "right daughter",
                                         "split var", "split point", "status",
                                         "prediction", "improve"))
  }


  if (labelVar) {
      tree <- as.data.frame(tree)
      v <- tree[[3]]
      v[v == 0] <- NA
      tree[[3]] <- factor(rownames(rfobj$importance)[v])
      if (rfobj$type == "classification") {
          v <- tree[[6]]
          v[! v %in% 1:nlevels(rfobj$y)] <- NA
          tree[[6]] <- levels(rfobj$y)[v]
      }
  }
  tree
}

Try the extendedForest package in your browser

Any scripts or data that you put into this service are public.

extendedForest documentation built on Dec. 12, 2023, 3 p.m.