I have a function which does extra things if a non-empty value is supplied to what otherwise would be an optional parameter. If the argument is not supplied, the function doesn't do anything extra.
Is it better to use NA
or NULL
? What are the advantages of either?
For example, if I use NA
, then I can quickly check which arguments were not supplied by using: is.na(as.list(environment()))
in the function body, which does not work with is.null
.
Here is an example of why I want to use NA
I am trying to build an R connector to the Geckoboard bar chart API. It has many optional arguments. If I do the following, it is very easy to use the package jsonlite
to supply the optional arguments.
get_barchart_json <- function(data, x_axis = list(labels = NA, type = NA), y_axis = list(format = NULL, unit = NULL)){
payload <- "{"
textappend(payload) <- '"series": [{"data":['
textappend(payload) <- paste0(data, collapse = ",")
textappend(payload) <- ']}]'
if(any(!is.na(x_axis))){
textappend(payload) <- ","
textappend(payload) <- jsonlite::toJSON(x_axis, auto_unbox = TRUE)
}
if(any(!is.na(y_axis))){
textappend(payload) <- ","
textappend(payload) <- jsonlite::toJSON(y_axis, auto_unbox = TRUE)
}
# finish construction
textappend(payload) <- '}'
return(payload)
}
which returns, for example:
cat(get_barchart_json(data = c(1,2,3,4), x_axis = list(labels = c("a", "b", "c", "d"), format = "text"), y_axis = list(format = 'decimal')))
NB: textappend
is:
`textappend<-` <- function(payload, value){
payload <- paste0(payload, value)
payload
}