[SOLVED] Extract operator `$( )` and non-syntactic names

Issue

Say I have the following list (note the usage of non-syntactic names)

list <- list(A  = c(1,2,3),
            `2` = c(7,8,9))

So the following two way of parsing the list works:

`$`(list,A)
## [1] 1 2 3

`$`(list,`2`)
## [1] 7 8 9

However, this way to proceed fails.

id <- 2 
`$`(list,id)
## NULL

Could someone explain why the last way does not work and how I could fix it? Thank you.

Solution

Your id is a "computed index", which is not supported by the $ operator. From ?Extract:

Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does. x$name is equivalent to x[["name", exact = FALSE]].

If you have a computed index, then use [[ to extract.

l <- list(a = 1:3)
id <- "a"

l[[id]]
## [1] 1 2 3

`[[`(l, id) # the same
## [1] 1 2 3

If you insist on using the $ operator, then you need to substitute the value of id in the $ call, like so:

eval(bquote(`$`(l, .(id))))
## [1] 1 2 3

It doesn’t really matter whether id is non-syntactic:

l <- list(`[email protected]#$%^` = 1:3)
id <- "[email protected]#$%^"

l[[id]]
## [1] 1 2 3

`[[`(l, id)
## [1] 1 2 3

eval(bquote(`$`(l, .(id))))
## [1] 1 2 3

Answered By – Mikael Jagan

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *