R/grnn.margin.R

Defines functions grnn.margin

Documented in grnn.margin

#' Derive the marginal effect of a predictor used in a GRNN 
#'
#' The function \code{grnn.margin} derives the marginal effect of a predictor used in a GRNN
#' by assuming mean values for the rest predictors
#'
#' @param net  The GRNN object generated by grnn.fit() 
#' @param i    The ith predictor in the GRNN
#' @param plot TRUE or FALSE to plot the marginal effect
#'
#' @return A plot of the marginal effect or a dataframe of the marginal effect
#'
#' @seealso \code{\link{grnn.partial}}
#'
#' @examples
#' data(iris, package = "datasets")
#' Y <- ifelse(iris[, 5] == "setosa", 1, 0)
#' X <- scale(iris[, 1:4])
#' gnet <- grnn.fit(x = X, y = Y)
#' grnn.margin(gnet, 1, plot = FALSE)

grnn.margin <- function(net, i, plot = TRUE) {
  if (class(net) != "General Regression Neural Net") stop("net needs to be a GRNN.", call. = F)
  if (i > ncol(net$x)) stop("the selected variable is out of bound.", call. = F)
  if (!(plot %in% c(T, F))) stop("the plot input is not correct.", call. = F)

  xname <- colnames(net$x)[i]
  n <- length(unique(net$x[, i]))
  x <- matrix(rep(colMeans(net$x), n), nrow = n, byrow = T)
  x[, i] <- sort(unique(net$x[, i]))
  rst <- data.frame(x = x[, i], p = grnn.predict(net, x))
  if (plot == TRUE) {
    plot(rst[, 1], rst[, 2], type = "b", lty = 4, lwd = 3, ylab = '', xlab = xname,
         main = "Marginal Effect", pch = 16, cex = 1.5, col = "red", cex.main = 1, cex.lab = 1, yaxt = 'n')
    rug(rst[, 1], col = 'green4', ticksize = 0.03, lwd = 3)
  } else {
    return(rst)
  }
}

Try the yager package in your browser

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

yager documentation built on Oct. 26, 2020, 1:06 a.m.