Home > Net >  R: extract operator `$( )` and non-syntactic names
R: extract operator `$( )` and non-syntactic names

Time:01-24

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:

You can use [ instead:

id <- 2

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

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, ", eval(substitute(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)

  •  Tags:  
  • Related