Reputation: 1613
Are there existing services to minify R code? Seems easy to find a JS minifier, I have not yet found something similar for R. I'd be happy with an Atom extension or a web-based service
Upvotes: 3
Views: 619
Reputation: 46
You can leverage R's internal parser to minify code. For example, if you have some text like:
myList <- list(a = 1,
b =2
,c = list( a = 1,
b = 2)
)
myOtherList <- list(a = 1,
#My comment
b = 1)
in a file called myFile.R
You can parse the expression and then coerce it to a character, something with a call like:
paste(as.character(parse(text = text)),collapse = "\n")
which will output an expression per line, without comments:
myList <- list(a = 1, b = 2, c = list(a = 1, b = 2))
myOtherList <- list(a = 1, b = 1)
This is a fun example of using parsed code and doing modifications to it. Parsing as a tool creates a whole new world of opportunity for a developer. I would recommend readings Peter Norvig's lisp interpreter in python as an entry point to code grammar, parsing and abstract syntax trees(ASTs) : http://norvig.com/lispy.html
If indeed you wanted to minify the code symbolically as well (replace myVarName
with a
for example) You would be able to use the AST returned and reassign all the variables to a "minified" version, and then dump the code.
Hope this helps!
Upvotes: 3