colinfang
colinfang

Reputation: 21707

How to use `[[` and `$` as a function?

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)

Upvotes: 5

Views: 176

Answers (1)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

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

Upvotes: 7

Related Questions