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?
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With