Objects completion in lists with the cashtag ($) symbol

Viewed 45

Good morning everyone,

I have a very simple question.

foo <- list(bar=2)

As you all know, I can access the bar object with brackets or using the cashtag ($) symbol.

> foo$bar
[1] 2
> foo[["bar"]]
[1] 2

If I replace bar with ba, I will get the same result with the cashtag ($), but a different one with the brackets.

> foo$ba
[1] 2
> foo[["ba"]]
NULL

Is there a way to obtain the result NULL instead of 2 using the cashtag ($) in this situation?

2 Answers

I don't believe it's possible to get it to return NULL unless there is something else in the list that also partially matches the input. So if there was an element in your list named bak then foo$ba would return null since the partial match wasn't unique.

> foo <- list(bar=2)
> foo$ba
[1] 2
> foo$bak <- NA
> foo$ba
NULL

You can also turn on an option to give a warning if/when a partial match happens.

> options(warnPartialMatchDollar = TRUE)
> foo <- list(bar = 2)
> foo$ba
[1] 2
Warning message:
In foo$ba : partial match of 'ba' to 'bar'

but as you can see it still returns the value from the partial match. If you want it to return NULL in the case of a partial match then I just suggest using [[ instead of $ and in general it's probably just a better idea to use [[ anyways.

I just found a way using @Dason help.

options(warnPartialMatchDollar = TRUE)

foo <- list(bar=2)
tryCatch(foo$b, warning=function(x){NULL})

It will be just fine for my needs.

Thank you for the hint!

Related