Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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)

like image 365
colinfang Avatar asked Sep 12 '13 10:09

colinfang


1 Answers

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
like image 60
Simon O'Hanlon Avatar answered Oct 16 '22 07:10

Simon O'Hanlon