JelenaČuklina
JelenaČuklina

Reputation: 3762

convert `NULL` to string (empty or literally `NULL`)

I receive a list test that may contain or miss a certain name variable.

When I retrieve items by name, e.g. temp = test[[name]] in case name is missing I temp is NULL. In other cases, temp has inadequate value, so I want to throw a warning, something like name value XXX is invalid, where XXX is temp (I use sprintf for that purpose) and assign the default value.

However, I have a hard time converting it to string. Is there one-liner in R to do this?

as.character produces character(0) which turns the whole sprintf argument to character(0).

Workflow typically looks like:

for (name in name_list){
  temp = test[[name]]
  if(is.null(temp) || is_invalid(temp) {
    warning(sprintf('%s is invalid parameter value for %s', as.character(temp), name))
    result = assign_default(name)
    } else {
    result = temp
    print(sprintf('parameter %s is OK', name)
    }
  }

PS. is_invalid is function defined elsewhere. I need subsitute of as.character that would return '' or 'NULL'.

Upvotes: 1

Views: 1956

Answers (3)

jakob-r
jakob-r

Reputation: 7282

You can use format() to convert NULL to "NULL".

In your example it would be:

    warning(sprintf('%s is invalid parameter value for %s', format(temp), name))

Upvotes: 1

d.b
d.b

Reputation: 32558

test = list(t1 = "a", t2 = NULL, t3 = "b")

foo = function(x){
    ifelse(is.null(test[[x]]), paste(x, "is not valid"), test[[x]])
}

foo("t1")
#[1] "a"

foo("t2")
#[1] "t2 is not valid"

foo("r")
#[1] "r is not valid"

Upvotes: 3

JelenaČuklina
JelenaČuklina

Reputation: 3762

Well, as ultimately my goal was to join two strings, one of which might be empty (null), I realized, I just can use paste(temp, "name is empty or invalid") as my warning string. It doesn't exactly convert NULL to the string, but it's a solution.

Upvotes: 0

Related Questions