Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make access to non-existant list element an error

Tags:

r

In R, one can access list elements with $. When one accesses a field which is not included in the list, the resulting value is just NULL. This is problematic in the parts of my code where I further work with object. Take this code:

l <- list(foo = 1, bar = 2)
print(l$foobar)

The output will just be NULL and no error and no warning. I am aware that this might be needed such that assignment of new elements (l$foobar <- 3) can work.

Is there some way where I can make read-access of a field in a list a hard error if it does not exist?

like image 480
Martin Ueding Avatar asked Jan 30 '18 17:01

Martin Ueding


1 Answers

An extreme option is to overload the $ operator, then define an S3 method for list objects that checks the names.

`$` <- function(x, y) { 
  UseMethod("$")
}

`$.list` <- function(x, y) {
  ylab <- deparse(substitute(y))
  stopifnot(ylab %in% names(x))
  do.call(.Primative("$"), list(x, ylab))
}

Then:

myList <- list('a' = pi)

> myList$b
Error: ylab %in% names(x) is not TRUE

> myList$a
3.141593

You must, of course, be sure to set the following:

`$.default` <- base::`$`

to avoid any conflict with existing usage of the "$" operator

If you wish to continue to use partial matching with the "$" when applied to a list, you can make use of stopifnot(length(pmatch(ylab, names(x)))>0).

like image 94
AdamO Avatar answered Oct 11 '22 07:10

AdamO