Search code examples
rstringnulltype-conversion

R: Ho to convert `"NULL"` into `NULL`?


How do you convert a string that says NULL ("NULL") into an actual NULL value in R?

I am getting an envvar that contains either a string or "NULL" (also a string) and my R code is looking for either a string or NULL. This looks so simple but for example stringr::str_replace_all("test", 'NULL', NULL) does not work:

> stringr::str_replace_all("test", 'NULL', NULL)
Error in `stringr::str_replace_all()`:
! `replacement` must be a character vector, not `NULL`.

Solution

  • I managed to get it going with a simpler if/else:

    fun(
    base.url = if (Sys.getenv('BASE_URL') == 'NULL') {as.null()} else {Sys.getenv('BASE_URL')}, ...) {
    ...
    }