I have a function that does extra things if a non-empty value is passed to what would otherwise be an optional parameter. If no argument is specified, the function does nothing more.
Is it better to use NAor NULL? What are the benefits?
For example, if I use NA, then I can quickly check which arguments were not provided using: is.na(as.list(environment()))in the body of a function that 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 for the Geckoboard histogram API . It has many optional arguments. If I do the following, it is very simple to use the package jsonliteto provide 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)
}
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::
`textappend<-` <- function(payload, value){
payload <- paste0(payload, value)
payload
}