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, "[[", "...">

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 tried to use $ in the same way

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

In addition, is it possible to use the operator as a function, for example, other languages?

eg. a + b equivalent to (+)(a, b)

+5
source share
1 answer

You can use an anonymous function with $ . I would suggest that this has something to do with the fact that the $ arguments were never evaluated ...

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

And to answer your second question ... Yes, all binary arithmetic operators can be specified using inverse ticks, for example ...

 a <- 2 b <- 3 # a + b `+`( a , b ) [1] 5 # a ^ b `^`( a , b ) [1] 8 # a - b `-`( a , b ) [1] -1 
+7
source

Source: https://habr.com/ru/post/953701/


All Articles