5

I know I can do this:

x <- list(a=1, b=1)
y <- list(a=1)
JSON <- rep(list(x,y),10000)
sapply(JSON, "[[", "a")

However, I struggled at use $ in the same way

sapply(JSON, "$", "a")
sapply(JSON, "$", a)

Also, is it possible to use operator as a function like other languages?

e.g. a + b is equivalent to (+)(a, b)

colinfang
  • 20,909
  • 19
  • 90
  • 173

1 Answers1

7

You can, you just need to use an anonymous function with $. I would guess that this has something to do with the fact that $'s arguments are never evaluated...

sapply(JSON, function(x) `$`( x , "a" ) )

And to answer your second question... Yes, all binary arithmetic operators can be specified using back ticks, like so...

a <- 2 
b <- 3

# a + b
`+`( a , b )
[1] 5
# a ^ b
`^`( a , b )
[1] 8
# a - b
`-`( a , b )
[1] -1
Community
  • 1
  • 1
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
  • Actually regular quotes usually work as well: `'+'(1,1) [1] 2` – IRTFM Sep 12 '13 at 13:02
  • 3
    @DWin Possibly not always though... From the bottom of `?Quotes`: *Such identifiers are also known as syntactic names and may be used directly in R code. Almost always, other names can be used provided they are quoted. The preferred quote is the backtick (`\``), and `deparse` will normally use it, but under many circumstances single or double quotes can be used (as a character constant will often be converted to a name). One place where backticks may be essential is to delimit variable names in formulae: see `formula`.* – Simon O'Hanlon Sep 12 '13 at 13:08