I hate R, volume 38942

link

R doesn’t allow block comments. You have to comment out each line, or you can encapsulate the block in if(0){} which is the world’s biggest hack. Grrrrr.

P.S. Just to clarify: I want block commenting not because I want to add long explanatory blocks of text to annotate my scripts. I want block commenting because I alter my scripts, and sometimes I want to comment out a block of code.

75 thoughts on “I hate R, volume 38942

      • You’re not the only one to report that. Or to report that Rstudio just crashes even when you don’t have RStan running (love the contrast in capitalization styles). It also monkeys with I/O streams in a way I don’t understand. I just stay away from it and run R in the terminal.

      • I’ve had a few crashes when using rstudio and stan, but I’ve never confirmed it was actually due to stan. It hasn’t happened in a long while either.

        However, I’m not sure I’ve ever had a crash with stan and rstudio using rstudio-server, which I prefer using anyway (because I can get back to whatever I was doing from wherever I’m at, and my “server” [my home desktop] is way more powerful than any machine I’ll see on campus or my laptop).

        • Lo and behold, rstudio crashed when using stan_dens(), and now that I think about it, I think stan’s plotting commands (not sure if bayesplot does the same thing) tended to crash my session in rstudio in the past. (But not rstudio-server, oddly enough).

      • I’m a long time RStudio user, and I’ve used Stan a ton of times with it, and I’ve never noticed it crash because of Stan. It crashes from time to time with other things, but for R I think it’s a pretty good IDE. It even has editing support for Stan files, if I remember correctly.

      • A good editor (vim, emacs, RStudio whatever) makes the need for block comment syntax somewhat redundant since you can comment out multi line blocks pretty damn easily.

      • What is the value of block commenting? How is it better than single-commenting multiple lines in batch with Shift+Ctrl+C?

        Another tip, in RStudio, you can put 4 dashes in a row at the end of a comment if you want to make a collapsible section header.

        Also, there’s R Notebooks and R Markdown for making code more comment-friendly (allows for Markdown sections)

        • Brent:

          See my P.S. in the above post.

          Also, you might not see any value in block commenting, but many people do! Lots of languages do have block commenting, and I find it to be a useful feature.

        • I’m a true believer in RStudio and all that it does, but sometimes I just want to block comment some code out. The other way that Andrew’s not mentioned is to write all your analysis as an R Markdown document and use HTML block commenting. But that’s a little bit like loading your bike on to a bus because you want to ride down to the shops but there’s no bike lane.

  1. If you are using RStudio, you can highlight and then block comment/uncomment using the keyboard shortcut Command+Shift+C (Mac) or Ctrl+Shift+C (Win/Linux).

    • In most situations, this is just going to make matters worse. It means you have to learn a new system of markdown with very sketchy doc (Rstudio’s is better than most, but it’s hardly a spec, so I’m reduced to trial and error every time). And it means you have to learn how that markdown system communicates with R. It just adds another layer of complexity. Certainly not worth it for comments! Sort of in the vein of “I’ll try to solve that problem with regular expressions, so now I have two problems”, for which, of course, there’s an xkcd strip.

      In general, I think commingling code and text is a bad idea. There aren’t tools that work well for editing both, and it makes it hard to scan just the code when it’s buried in text. Similarly, if any of those programs take more than a few seconds to run, it becomes unbearably slow to update the paper because running everything gets tied together (there is an upside to that in maintaining consistency). This isn’t a gripe about knitr per se, but about the whole “literate programming” movement. Instead, I would recommend reading Google’s coding style for suggestions on how and what to comment in code (there are lots of sensible guides out there once you leave the R world).

      I do hate knitr’s style sheets. Does anyone know of one that obeys basic typographic principles of alignment and contrast and color?

      • +1 to “In general, I think commingling code and text is a bad idea”.

        I think knitr and such are great but I don’t understand why that is necessary for a full paper, primarily for all the reasons Bob mentions. It’s also only feasible if all co-authors are fully R/markdown/TEX literate and have fully bought into the literate programming movement (a situation I have yet to encounter). I’d like to see more people articulate this. That said, I think knitr/markdown are great for writing labs, lecture notes, tutorials, and very short reports.

        • I completely agree that knitr’s great for writing short presentations. I used it for all my Stan case studies. I haven’t used Jupyter much myself, but have enjoyed presentations I’ve seen using it. We’ll be using bookdown for our Stan books, so I’ll have more to report on that as it goes. It’ll mean our style will have to be minimal, but judging from Hadley’s Advanced R book, it’s possible to get a workmanlike set of web pages and an almost passable book style out the other end. Yihui Xie’s advice to just work on the HTML output, then take a final pass on the LaTeX is a good one. What I wonder about is how much work went into post-processing the LaTeX.

          Luckily, I’ve been in stats and computer science, where everyone knows enough LaTeX to at least write a paper. I’ve personally been using LaTeX+emacs for over 30 years. LaTeX’s a disaster in so many different ways (starting with character encodings and the world’s most baroque install and macro system), but it generates great docs. I have about the same relationship to it as I do to R—it’d be great if someone wrote a modern version from the ground up, but then I’d lose all the packages I need!

        • Lol, I feel the same way about latex. It’s an ongoing love/hate relationship.

          Latex makes really complicated things really simple (hyperlinked ToC, references, complex math, enumeration of sections/formulae/citations/links/figures/tables), but really simple things really complicated (custom templates, changing list styles, changing fonts…).

          I want to like markdown more, but the spec is so varying across implementations it drives me crazy. Plus, it still can’t handle all the formatting that I want for papers in particular, and changing the style of html-based outputs requires a pretty heavy use of CSS, which I also don’t like using.

          I’ve looked for latex alternatives, and even if latex is really cludgy, difficult to program in (luatex doesn’t really improve this much as an end user, just for devs), etc, it still seems like the best option, and that is so disappointing.

          I wrote my master’s thesis in latex, and in the results section I typed 0 numbers manually. I used R to generate all tables, figures, and in-text results in the case that my data would need to be tweaked a bit. Sure enough, there were a few cases I needed to drop, but rather than spend days moving the new estimates, tables, and figures over to the manuscript and double checking to ensure everything was in sync, I just hit ‘re-compile’, and it was glorious. That said, FORMATTING the stupid thesis was an atrocious process that required me to load the APA6 style and do some major manual tweaking of things like formatting section headers and the TOC, both which are stupidly difficult to do.

      • I’m working on a project where I only get time to work on it every so often. My current approach is to just dump huge quantities of notes into an Rmd file and knitr it together. It’s like an enormous lab notebook with auto-generated graphs and links to online sources and all run together. I enjoy this way of working on this kind of project.

        On the other hand, if I’m actually trying to produce a finished polished document I could imagine I’d abandon this method and just have an R script that generates all the output I need and a LaTeX document that slurps it up.

      • Do you feel the same way about commingling equations and text? For my use cases, they’re functionally identical: here’s text describing something, probably a methods or results section; now here’s code/math telling you exactly what I did and how to reproduce it. They’re right next to each other so you don’t have to go back and forth between two sections of the paper and try to piece together which parts go together.

      • For styles, isn’t there a Tufte stylesheet? Maybe not your style, but definitely something that pays attention to typography and layout principles.

        For Rmarkdown and emacs, there is polymode (https://github.com/vspinu/polymode). Incidentally, I have a pull request in progress there that makes running code from an Rmarkdown document easy. I’ve been using it for a few weeks and liking it. We are trying to decide on an interface, so we/I would welcome feedback from any Rmarkdown + emacs users in the house (https://github.com/vspinu/polymode/pull/129).

      • In vignettes at least you get the code separated out, which is quite nice. I agree that it is definitely not for code comments which are for a different audience and purpose. , Obviously the issue Andrew is having has nothing to do with that purpose either.

        I do actually really like code and text together for certain tasks (and it is great for students). I give them a markdown file with content to read, tasks to do and questions to answer etc.

    • Forgive me if this is obvious but…

      The stated problem is to have multiline comments to “turnoff” blocks of code.

      You can always set an RMarkdown chunk to eval=F, which means it is not evaluated.
      Or (easier) just convert {r mychunk} to {} to stop evaluation. I do both routinely.
      To add a true multiline comment, you can embed a comment in a non-evaluated block like:
      “`{}
      Random words
      More random words
      “`

      And you can extract only the R code by using purl, of course. And you can set an rmarkdown chunk option purl=FALSE to eliminate a chunk from the purl output.

      I love multiline comments in Python, so I get the point. But this is not a terrible workaround and better than the if monstrosity that was mentioned (NO!!), iMHO.

  2. I would also recommend RStudio, which also allows you to continue commenting after pressing enter (“continue commenting when insertig a new line”), however, you have to delete the comment sign when you want to stop commenting.

    • M-+ isn’t bound to anything on my Emacs, but M-x comment-region works just fine, and C-u M-x comment-region uncomments the region.

      With ESS (I presume that’s who is doing it), Emacs knows the proper comment syntax. One nice feature: that’s mode-specific, so Emacs uses the appropriate commenting for the language you’re using–one command works for pretty much anything. You can bind it to M-+, as Frans did, if you want. With command completion, you don’t have to type the whole command, though.

      See C-h f comment-region and M-x apropos RET comment RET for more options (apropos is probably bound to C-h a on most Emacs). Hmm. apropo showed me ess-fix-comments and ess-indent-with-fancy-comments, which led to ess-style-alist. Scroll down in its help to see the value options. For example, there’s a C++ style, a K&R style, and at least four different styles for R. You can customize any of them, if you don’t like the predefined versions.

      • Frans meant to write M-; , which is bound to comment-dwim. Here’s the help page:

        > Call the comment command you want (Do What I Mean).
        > If the region is active and ‘transient-mark-mode’ is on, call
        > ‘comment-region’ (unless it only consists of comments, in which
        > case it calls ‘uncomment-region’).

  3. You could just wrap it in quotes, right? It’s also a hack because the quote will be evaluated as a string by the interpreter, but this is essentially what Python programmers do with the triple quotes around multi-line comments.

    • If you wrap something in quotes, you can’t see that it’s a comment by just scanning it. The whole point of code formatting, like punctuation and capitalization in written language, is to make the text easier to read.

  4. Why don’t you just write your comment on a single really, really, really long line? There’s no character limit. Your collaborators will hate you, but who needs collaborators?

    Joking aside, apparently there’s an R package that will clean up such long lines: https://yihui.name/formatr/

  5. This has nothing to do with R, but rather the text editor you use. In sublime text just do ctrl-shift-/ to block comment (or reverse), of course you can change this if desired. Also, I don’t think the if(FALSE){} solution is so bad.

  6. I agree with this post. Multi-line commenting would be nice.

    I’ve basically trained myself to just type my comment in the .R file with linebreaks and everything, then (I use vim/vim bindings), 0, ctrl+v, 5j (if there are 5 lines), shift+I, #
    Which is actually fairly quick once you get used to it (basically, go to beginning, select vertically, insert vertical, comment symbol), or one could use their editor’s ‘make these lines comments’ commands, but these are all just hacks around a problem that was solved prior to 1970: block quote. I don’t think it would even be a hard addition to the language; what if block quotes were just #/ stuff here /#

  7. +1 and -1 to commingling code and text.

    +1

    I’ve only used Rstudio and Rmarkdown a little, but seems pretty straightforward in org mode. Org gives me tools that work well for working on the text I’m touching at the time–R, org source, or whatever other language I might want to try. I work in a Windows environment, but I almost never type a Word document. Rather, I produce it in org, export it for Word, and then (because I haven’t mastered all the style stuff I’d need) tweak the layout in Word–or I just export it via pdflatex.

    Most of the people I give reports like seeing the literate approach, for they can see what I did and why. For those who don’t, I can choose what I export by block to hide the code they don’t want to see.

    Learning all the permutations of org options and block headers I might want to achieve the results I want is a bit of a climb.

    -1

    I’m discovering it’s possible to write sloppy code that way, code that has unnecessary dependencies on other blocks (perhaps that’s true in Rstudio, too?). I can tangle it to produce the entire script as one R file, but I may have to do a bit of work to reuse a snippet from one org code block.

    My solution? Create functions in a package, and then use the package in my literate document–or write functions in org source blocks as if I were writing a package. With a bit of organization, that seems to work.

  8. Dear Andrew,

    In Sublime Text, you could do the following:
    https://www.youtube.com/watch?v=AnvEp7RhmT0

    If you look at the bottom left of the search/replace bar, there are a series of icons including one for use of regex, and one for only changing things in the selected area. And rather than ‘id’ you will be adding # up front.

    The other alternative is to convert entire block to a string literal by doing

    code
    code
    code

    ideally, of course, we would want native support for multi-line comments and it is easy enough to implement and something base R people could do pretty easily.

  9. What is really annoying is how the lack of pass-by-reference makes functional modularity harder. (I.e., if you don’t want to recopy big dataframes over and over, you need to make your functions refer to global variables.) Any solutions appreciated.

    • check the data.table package. I think what’s technically going on is that R passes a reference with copy-on-write semantics. So it’s doing foo[bar] <- baz that causes the copy.

      data.table does this differently, and makes things a lot more efficient for passing around large tables.

      On the other hand, I am not a fan of the idea of passing a table to a function so it will mangle it for me. Rather than

      fix.up.this.table(my.table)

      I'd rather use
      my.new.table = transform.my.table(my.table)

      and I think data.tables does this memory efficiently. In any case, whenever I need an enormous data frame I use the data.table class.

    • Actually, R does have pass by reference.

      The easiest way to use them is with environments. They are kinda like lists, but not quite. For example:

      myEnv = new.env()
      add_a = function(obj){
      obj$a = ‘cat’
      }
      add_a(myEnv)
      myEnv$a

      The much trickier way to use them is with reference classes. Think OO classes, but without the speed.

      • Note: copy and pasting the above code will not run because the quotation marks got mangled. Retyping it will work. Personally, that’s what annoys me most about R, (or really any programming language); emailing a quick solution to a co-worker and then spending 4 hours trying to figure out why it’s not working on their side even though it’s letter by letter equivalent to what you have on your end.

  10. Shouldn’t you just use version control and delete the code you are commenting?

    I mean I know commenting blocks can be more convenient, but, I feel too many “coding but not programming” disciplines are missing out on version control.

  11. If you’re working on anything larger than about 5+/-2 lines of code without emacs, you’re wasting your time. ESS is my favorite interface for “raw” R interaction. (Note : the “use-emacs” trigger is user-dependent ; being probably the worst typist still alive, my trigger is closer to 3 lines… But YMMV).

    Comments : use emacs’ “`comment-region“`. Can’t be simpler…

    Text-and-code : Yes, I’ve tried Markdown in its various incarnation (including a brief trial of RStudio. I find myself returning to “the usual” : emacs + ESS + polymode + knitr + \LaTeX (+ Sage + sage_shell_mode if I need symbolic computation…) : there’s always something I need that doesn’t exist in any given version of Markdown, or is not supported.

    I find Jupyter handy for “early” work (nice scratchpad), but knitr’s “cache” feature is infuriatingly useful for anything serious (“infuriatingly” because it sometimes (rarely) seriously messes things up…). In preparatory work, using Jupyter’s Sage kernel, with %%r cells whenever needed is useful. But you don’t get the cache feature.

    • Cugrad:

      I think there are still one or two R users still left in industry. They’ll probably be switching to COBOL soon enough, but for now it can still be useful to communicate with these legacy users.

    • Matt:

      Please look at my P.S. above! I have no interest in adding long blocks of comments to my code. But sometimes I’m playing with analysis and I want to comment out a block of code. This is trivial to do in C++ but there’s no easy way to do it in R.

Leave a Reply

Your email address will not be published. Required fields are marked *