简体   繁体   中英

R pass “blank” or “missing” arguments to package function with if else statement

My specific issue is with using heatmap.2 with shiny server, but I imagine this question is applicable in more places.

I want to make an argument optional, but the argument itself doesn't have a NULL/FALSE default value from what I can gather. I am trying to do this with the RowSideColors and ColSideColors options from heatmap.2.

It seems that defining the argument and leaving it blank works, as well as creating a missing_arg via rlang. But when you incorporate either of these into an if statement, heatmap.2 doesn't like it.

Any ideas?

library(rlang)
library(gplots)

data(mtcars)
x  <- as.matrix(mtcars)

missing <-missing_arg()
row_clusters <- 0

#works
heatmap.2(x, RowSideColors= )
heatmap.2(x, RowSideColors= missing )

#doesn't work
heatmap.2(x, RowSideColors= FALSE)
heatmap.2(x, RowSideColors= NULL)
heatmap.2(x, RowSideColors= NA)
heatmap.2(x, RowSideColors= NaN)
heatmap.2(x, if(row_clusters == 0)RowSideColors= )
heatmap.2(x, if(row_clusters == 0)RowSideColors= missing )
heatmap.2(x, RowSideColors= if(row_clusters == 0){missing}else{})
heatmap.2(x, RowSideColors= if(row_clusters == 0) missing else missing)
etc...

For context, here is what is happening in the background for RowSideColors and ColSideColors in heatmap.2:

if(!missing(ColSideColors)) { ## add middle row to layout
        if(!is.character(ColSideColors) || length(ColSideColors) != nc)
          stop("'ColSideColors' must be a character vector of length ncol(x)")

I was surprised heatmap.2(x, RowSideColors= if(row_clusters == 0) missing else missing) didn't work... I think the issue is the missing_arg is fragile... see the Fragility of the missing argument object section of ?missing_arg . This works:

rowside_arg <- if(row_clusters == 0) missing_arg() else missing_arg()
heatmap.2(x, RowSideColors = arg)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM