barbone,

I recently found out I can do parenthetical method chaining (there's a real term for this right?) in like the examples below.

args <- (  
 scribe::command_args()  
 $add_argument("foo", action = "flag")  
 $add_argument("bar", action = "list", default = 1)  
 $parse()  
)  
wb <- (  
 openxlsx2::wb_workbook()  
 $add_worksheet()  
 $add_data(x = datasets::attitude)  
)  

I think I'm going to update a lot of scripts now.
@RStats

dgkf,
@dgkf@fosstodon.org avatar

@barbone Another option which might be a bit more idiomatic in the pipe-loving R world is to use the lesser-known %$% operator from magrittr - naturally not a viable path if you're trying to limit dependencies.

library(magrittr)

args <- scribe::command_args() %$%  
 add_argument("foo", action = "flag")  

(also, TIL about scribe and it looks awesome)

barbone,

@dgkf Unfortunately this will not work when you try to call a method with a 'conflict' in your search path. For example, the $parse() method of the scribeCommandArgs object will fail because of base::parse()

dgkf,
@dgkf@fosstodon.org avatar

@barbone Ah, I didn't even think of that (and clearly didn't write out enough of the example to see it for myself). It would totally bite me half way through a script.

mjskay,

@dgkf @barbone If you want to write against this type of API in a pipe-y way you can use $:

args <- some_function()$  
 something_else("foo")$  
 another("bar")$  
 more()  

No need for parens or %$%

and I guess if you really want it to look pipe-y you could add a space

args <- some_function() $  
 something_else("foo") $  
 another("bar") $  
 more()  
urswilke,
@urswilke@fosstodon.org avatar

The important part is to put the $ at the end of the line and not in the next line, as R then continues to parse the following line and perceive it as one expression,
(Like with pipes, but also works for other stuff like +, &, etc...).
In other words: as long as it's not a complete expression at the end of the line, the parser continues adding the following line.
I think I recently read that somewhere but I forgot where

  • All
  • Subscribed
  • Moderated
  • Favorites
  • random
  • rosin
  • thenastyranch
  • anitta
  • normalnudes
  • GTA5RPClips
  • DreamBathrooms
  • mdbf
  • magazineikmin
  • Youngstown
  • ngwrru68w68
  • slotface
  • InstantRegret
  • kavyap
  • cubers
  • tester
  • cisconetworking
  • provamag3
  • modclub
  • everett
  • osvaldo12
  • khanakhh
  • Durango
  • Leos
  • megavids
  • ethstaker
  • tacticalgear
  • JUstTest
  • lostlight
  • All magazines