Home > OS >  Extract operator `$( )` and non-syntactic names
Extract operator `$( )` and non-syntactic names

Time:01-25

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.

CodePudding user response:

I am also trying to get a better grasp of non-syntactic names. Unfortunately, more complex patterns of their use are hard to find. First, read ?Quotes and what backticks do.

For the purpose of learning here is some code:

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

id <- 2 

id_backtics <- paste0("`", id,"`")

text <- paste0("`$`(list, ", id_backtics, ")")
text
#> [1] "`$`(list, `2`)"

eval(parse(text = text))
#> [1] 7 8 9

Created on 2022-01-24 by the reprex package (v2.0.1)

CodePudding user response:

You can use [ instead:

id <- which(names(list) == 2) # 2 as the column name
# [1] 2                       # 2 as the position in the list

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

CodePudding user response:

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(`!@#$%^` = 1:3)
id <- "!@#$%^"

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

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

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