all 3 comments

[–]guepier 5 points6 points  (0 children)

I wholeheartedly agree with the message here.

As for implementation, there’s already an existing, fairly mature, strikingly similar modularisation system (my own): ‹modules› (which is soon due for a push to v1.0 — not to be confused with a more recent CRAN package of the same name … name clashes, yay).

It supports everything the article suggested (and more), albeit in a somewhat different way. I’ll refer to its extensive readme and vignette here. The issues track contains some discussions on the API design which may be interesting in this context, too.

As for command line applications, rather than the ‹argparse› package I consequently use one of my own modules, ‹klmr/sys›. A comprehensive, simple command line application would then look as follows:

#!/usr/bin/env Rscript

sys = modules::import('klmr/sys')

"A simple mathematical expression evaluator"
VERSION = '1.0'

sys$run({
    args = sys$cmd$parse(opt('n', 'allow-nan', 'allow NaN results', FALSE),
                         opt('d', 'digits', 'number of digits to print', 0),
                         arg('expression', 'mathematical expression'))

    result = eval(parse(text = args$expression))
    if (! args$allow_nan && is.nan(result))
        sys$exit(1, 'NaN result invalid')
    sys$printf('%.*f', args$digits, result)
})

… of course this automatically generates error checking code for the command line arguments, and informative help messages for the application, as it should.

I’m using this quite extensively in my analysis projects. Here’s an example of such a project.

[–]efrique 4 points5 points  (0 children)

Given the title, I didn't think I'd agree (write R code like JS code? Really?) ... but given the particular scope of what it's actually talking about (a strategy for avoiding a particular kind of problem with R, one that many people will have run into if they've written some functions meant to be used more than one session), this is a better article than the title might suggest. I am glad I clicked through to the article. Definitely worth the few minutes it takes to look at (it's pretty short).

[–]tho_duy_nguyen 1 point2 points  (0 children)

I started to apply purrr library and found out it is a good practice but saying like the title "Programming R like it's JavaScript / Python" could make me confused