我正在使用R中的Boruta包进行变量选择。Boruta在一张图中为我提供了一系列标准的箱线图,这很有用,但是鉴于我的预测变量过多,我希望能够限制boruta图中显示的箱线图数量。如下图所示。

r - R中的Boruta箱形图-LMLPHP

基本上,我想在图的右端“缩放”,但不知道如何使用boruta图对象。

谢谢,

先生

最佳答案

听起来像一个简单的问题,解决方案似乎令人费解。也许有人可以想出一种更快/更优雅的方式...

在这里,我基于源函数plot.Boruta创建一个新函数,并添加一个函数参数pars,该参数接受我们想要包含在图中的变量/预测变量的名称。

例如,我使用iris数据集来拟合模型。

# Fit model to the iris dataset
library(Boruta);
fit <- Boruta(Species ~ ., data = iris, doTrace = 2);
generateCol函数在内部由plot.Boruta调用,但未导出,因此不在包外部可用。但是,我们需要用于修改后的plot.Boruta例程的函数。
# generateCol is needed by plot.Boruta
generateCol<-function(x,colCode,col,numShadow){
 #Checking arguments
 if(is.null(col) & length(colCode)!=4)
  stop('colCode should have 4 elements.');
 #Generating col
 if(is.null(col)){
  rep(colCode[4],length(x$finalDecision)+numShadow)->cc;
  cc[c(x$finalDecision=='Confirmed',rep(FALSE,numShadow))]<-colCode[1];
  cc[c(x$finalDecision=='Tentative',rep(FALSE,numShadow))]<-colCode[2];
  cc[c(x$finalDecision=='Rejected',rep(FALSE,numShadow))]<-colCode[3];
  col=cc;
 }
 return(col);
}

现在,我们修改plot.Boruta,并添加一个函数参数pars,通过它过滤变量列表。
# Modified plot.Boruta
plot.Boruta.sel <- function(
    x,
    pars = NULL,
    colCode = c('green','yellow','red','blue'),
    sort = TRUE,
    whichShadow = c(TRUE, TRUE, TRUE),
    col = NULL, xlab = 'Attributes', ylab = 'Importance', ...) {

    #Checking arguments
    if(class(x)!='Boruta')
        stop('This function needs Boruta object as an argument.');
    if(is.null(x$ImpHistory))
        stop('Importance history was not stored during the Boruta run.');

    #Removal of -Infs and conversion to a list
    lz <- lapply(1:ncol(x$ImpHistory), function(i)
        x$ImpHistory[is.finite(x$ImpHistory[,i]),i]);
    colnames(x$ImpHistory)->names(lz);

    #Selection of shadow meta-attributes
    numShadow <- sum(whichShadow);
    lz <- lz[c(rep(TRUE,length(x$finalDecision)), whichShadow)];

    #Generating color vector
    col <- generateCol(x, colCode, col, numShadow);

    #Ordering boxes due to attribute median importance
    if (sort) {
        ii <- order(sapply(lz, stats::median));
        lz <- lz[ii];
        col <- col[ii];
    }

    # Select parameters of interest
    if (!is.null(pars)) lz <- lz[names(lz) %in% pars];

    #Final plotting
    graphics::boxplot(lz, xlab = xlab, ylab = ylab, col = col, ...);
    invisible(x);
}

现在,我们需要做的就是调用plot.Boruta.sel而不是plot,并指定我们要包含的变量。
plot.Boruta.sel(fit, pars = c("Sepal.Length", "Sepal.Width"));

r - R中的Boruta箱形图-LMLPHP

10-06 05:14
查看更多