Using Sublime Text 2 for R

My R interface has been pretty basic in the last few years. I have usually stuck to the R console. Yes, I’ve tried Emacs with ESS; a staple, but it is so unbearably antiquated that I always gave up on its significant learning curve. GUI packages–especially Rstudio–offer viable alternatives, but I feel the GUI lets me lose focus of the code. I have been envious of TextMate for Mac, but alas, I’m not a Mac user. Recently, though, I’ve moved to Sublime Text 2. With some nudging, I have been able to mimic the typical R console environment in the more-powerful Sublime Text program.

Want to skip to the basic instructions without the narrative? Just read the block quotes for specific instructions.

Sublime Text 2 offers a similar experience as TextMate (e.g., autocompleting parenthesis and quotation marks) and integrates well with R and other programming languages. R users aren’t the primary target and it takes a little kick to get the environment perfected for the R community. This is a little tutorial to give R users a similar experience with Sublime Text without ruining the program’s versatility. That is, you can have a familiar R experience and easily use Sublime Text with programming languages (e.g., JavaScript, C++) and typesetting programs (e.g., LaTeX, Markdown, MultiMarkdown).

This setup will let you

  • Browse R code with syntax highlighting
  • Use the familiar R console within Sublime Text
  • Send R code from a script to the R control (equivalent to Ctrl + R)
  • Organizing the layout so the script and console can be viewed simultaneously.
The first and last items are natively supported, but we’ll need to make some additional adjustments for the second and third item.

Initial Setup

I will presume some user knowledge here and will focus on the Windows user. Setup is very easy. Their website has links to executable autoinstallers, you won’t need to unzip and manual install nor are you depending on a third party to graciously compile code on your behalf.

Follow the instructions and install using the default settings.

Take a look around

R Syntax

Before proceeding, take a look at the R interface. Similar to other programs (e.g., Notepad++), Sublime Text offers native syntax highlighting for R code. Load one of your codes or try a sample script. If you don’t see any highlighting, you can always tell Sublime Text by clicking View  > Syntax and choosing R. Otherwise you can look in the lower right-hand corner as is shown in the image.

A nifty feature is autocompleting parenthesis and other special characters. Type “write.csv(” and it’ll auto-insert the right paren “)“. Little underlines help you match each left parenthesis with the right parenthesis. It also works with “{“, “[“, single, and double quotation marks.

Parenthesis and brackets are autoinserted

Comments have a lighter tone. So does the ubiquitous “<-“. Functions and special characters also have highlighting. If you don’t like the color scheme, you can change it under Preferences > Color Scheme. The default is Monokai, Twilight is a very dark theme while iPlastic is a very white theme.

Once you type a variable or function names, you can easily reference it later for autocompletion. Load the data into a variable called “sampleData” and you only need to type “sa” and hit tab to complete the name. If there are multiple possible matches, then you can use arrow keys to choose. The limitation of this, however, is that Sublime Text treats “sample.data” as two separate names. To counter this, I’ve started to use underscores, which is friendlier. Also, Sublime Text is using a simple approach–it simply refers to what you’ve typed before, it is not remembering variables in your memory the same way the GUI interfaces do.

Click on Preferences > Key Bindings – User, then copy and paste the following (thanks G-Force!)

// Characters that are considered to separate words – does not include periods.
// Place comma at the end of the line if there are multiple keybindings.
{"word_separators": "/\\()\"‘-:,;~!@#$%^&*|+=[]{}`~?"}

There are plenty of shortcuts. Select a few lines of code and press Ctrl + / to toggle comments. Ctrl + L will select the entire line based on your cursor. Ctrl + G, type in a number and you’ll jump to that line of code. Type Ctrl + : and type a variable name, it’ll find all instances. If you have multiple tabs, type Ctrl + P and you can jump to specific tabs.

At this point, however, you can’t execute or “compile” code. It’s just pretty font, helpful quirks, and shortcuts.

Package Manager

Our next goal is to be able use the R console and do calculations within Sublime Text. We’re going to use the SublimeREPL package to accomplish this. Don’t worry, this isn’t a rarefied thing that will clutter your RAM just for R; you’ll probably use this package for other things too.

Visit the Sublime Package Control website and follow the instructions to install the package manager on your computer.

CTRL + SHIFT + P to bring up the package manager

To access Package Manager type “Ctrl + Shift + P” to bring up a text box. Without using your mouse, begin to type “Install package” (without quotation marks). You may see a error related to git.exe, but you can ignore it at the moment.

Then type “SublimeREPL” and hit enter when it’s highlighted.

SublimeREPL essentially allows Sublime Text to access compilers or other programs. You can write in Sublime Text and send it to R for the computing. The results are sent back to Sublime Text for display. For you, it will operate like the normal R console.

However, we need to tell SublimeREPL where R is located on our computer. We need to add R to the Windows Path.

Find where R is installed. To do this, right click on your R icon–whether it’s start menu, desktop, or taskbar. Under the “Shortcut” tab, note the file path under “Target:”. Copy and paste this to a text document, you’ll need this shortly.

Now,

Click on Preferences -> Package Settings > SublimeREPL > Settings – User. Use the screenshot or example below and paste in the path (thanks Wojciech!).

For example, you might paste:

Notice in my example that I am ignoring (disabled) some packages I have installed. In order for this to work, I needed to add a comma after the bracket on line 8 and pasted the “default_extend_env” within the curly brackets.

Now you have told where Sublime Text can look to find R.

Open the R Console by clicking Tools > SublimeREPL > R. A window will pop up with the familiar R console header.

Further Customization: R Shortcuts

The R console is fantastic because you can quickly execute code from a script. SublimeREPL does have this capability, but the R user will want to use Ctrl+R, or something similar. Additionally, the native shortcut to execute script has some issues because it conflicts with other shortcuts already built-in Sublime Text.

Sublime Text calls these shortcuts “keybindings”. Fortunately, they can be edited. However, you have to be careful since Sublime Text has a lot of shortcuts and it’s easy to duplicate them, causing further issues.

I have a proposed set that should be pretty R user friendly. You can select some code (multiple, partial, or single lines) and run it in R using Ctrl + Shift + R. This is similar to the shortcut in the R console (a previous conflict prevents Ctrl + R without a lot of work).

To enable new keybindings:

Go to Preferences > Key Bindings – User and paste the code below. If something if already there, then append the code to the bottom (thanks Wojciech!).

You can also execute a line of code–without highlighting–using Ctrl + Alt + R. Select line(s) of code and send it to the console by typing Ctrl + Shift + R and then hitting R again. Similarly, display a line of code using Ctrl + Alt + R and then typing R again.

If you want to execute the entire script, type Shift + F7 and the entire file will be ran in R, no matter where your cursor is placed. I chose F7 because that is commonly used to compile code in other languages in Sublime Text.

A block of code can be sent by pressing Ctrl + Alt + Shift + R.  A block is the code between { }, such as a function. If you want to view the code before it’s executed, press Ctrl + Alt + Shift + R, then press R again.

Side-by-Side

It is difficult when the script is in one window and the console in another, but it’s easy to have the same feel as the R console.

To have the script and console side-by-side, click View > Layout. Choose either “Columns: 2” or “Rows: 2”, depending on your preference.

Switch between the side-by-side windows using Ctrl + 1 or Ctrl + 2.

Now you can see your script(s) and output side-by-side.

Drawbacks

The annoyances:

  • The console behaves like a text editor. Your cursor will need to be at the end of the line before you hit enter. Otherwise it just creates a linebreak.
  • When you use Ctrl + Shift + R (send selection) or Ctrl + Alt + R (send line), the console shows “>” every time a command is send. This is a little annoying, but moreso if there are errors in your code.
  • Sometimes the Ctrl + Shift + R or Ctrl + Alt + R is a little finicky, but I think I do it too quickly. Be deliberate if it does not seem to work.
  • When I am doing some heavy R computations, the setup can become slow. It has only happened once and could have ultimately been my fault. Let me know about any performance issues.

Besides R, Sublime Text can also handle other programming/scripting language. It can also handle typesetting languages, such as LaTeX or Markdown. SublimeREPL also works with other languages, such as Ruby and Python.

Credits

This is a tutorial that combines the work of others. This tutorial is just making gumbo from the recipes of others. In particular, Wojciech Bederski, who wrote the SublimeREPL package, which is key. Update: Wojciech also wanted to give props to hootener, who really supported the Windows R implementation for REPL.  Mads Hartmann Jensen wrote added the R support in REPL.  Obviously, the Sublime folks have put together a…uh…sublime program.

72 thoughts on “Using Sublime Text 2 for R

  1. Thank you for writing this wonderful tutorial and nice credits :).

    Some very minor tweaks and improvements (that are obviously not documented anywhere properly):

    1) PATH
    Env/PATH problems were so common, that now there is an easy way to solve them w/o the need to alter system preferences:
    From Sublime Text menu open: Preferences -> Package Settings -> SublimeREPL -> Settings – User
    and paste something like this (using R path found in previous steps):
    {
    “default_extend_env”: {“PATH”: “{PATH};C:\\Program Files\\R\\R-2.14.2\\bin\\i386”}
    }

    2) R Shortcuts
    You should not modify .\Packages\SublimeREPL\Default (Windows).sublime-keymap, because when a new version of SublimeREPL is released, it will get overwritten.
    Instead paste those keybinding to Preferenctes -> Key Bindings – User.
    F2 shortcuts that were interfering with ST2 bookmark function are now disabled by default, so there is no longer any need to alter installed .keymap.

    3) Credits:
    There is one more person directly responsible for pretty decent R support in SublimeREPL: hootener (http://www.sublimetext.com/forum/viewtopic.php?f=3&t=5802). Forcing R to work correctly on Windows was a surprisingly bumpy road and w/o hootener’s help I wouldn’t even try.

  2. Thank you so much for writing this, which is exactly what I was looking for. One question though – in the “Further Customization: R Shortcuts” section, you wrote “Copy and paste the contents of the code below”, but I didn’t see any code following that? Did I miss something? Thanks for your help!

    1. cabbagezs-

      Sorry, the problem was on my end. I recently changed hosts and the code was stripped from the post. I fixed it, so you should be able to see the code.

      Hope this helps!

  3. Thanks so much for this article. It helped me set up the Sublime+R environment. I am wondering if you happen to know in Sublime how I can send a break signal (just like pressing “esc” key in R console)? And is it possible that I define a hotkey which can send the current line of code to R and move the cursor to the next line?

    Thank you again!

    1. Chuck-

      I’m not aware of a way to send a break to the R console. It’s a good question and, trust me, if I find a way I will post an update. I have a bad habit of accidentally sending code that results in a huge output that I have to sit through.

      To execute code and move to the second line, the best approach is to make a macro. You could record a macro with Tools > Record Macro (Ctrl + Q) or write your own. Something like:

      [
      {"command": "repl_transfer_current", "args": {"scope": "selection"}}
      {"command": "move", "args": {"by": "lines", "forward": true}}
      ]

      Save this file somewhere with a “.sublime-macro” extension. Usually people save it in the Packages folder. Then, you can assigned it a keybinding. In this instance, we’ll use Ctrl + Alt + r, then press down again.

      { "keys": ["ctrl+alt+r", "down"], "command": "runMacroFile", "args": {"file": "path-to-macro-file-you-saved-here.sublime-macro"}},

      Here is a link to a gist, it might be clearer than this comment box. I didn’t try it before posting this comment, but you may want to swap “runMacroFileSilently” instead of “runMacroFile”.

      Side note, you can also go to Tools > Macros, but that never worked for me for some reason.

      Hope this helps!

      1. For some reason the break shortcut does not work for me neither.
        However there is an alternative from the menu: Tools > Cancel Build.

    2. Right clicking within the REPL window brings up a menu with an option “send other signal.” Sending the “SIGINT” signal is equivalent on unix to Ctrl-C. Haven’t tested this with R, but it works with MATLAB

  4. Typical R style guidelines suggest using periods instead of underscores to separate words. To get Sublime to treat words separated with a period as a single word, put this in your User settings file.

    // Characters that are considered to separate words – does not include periods.
    “word_separators”: “/\\()\”‘-:,;~!@#$%^&*|+=[]{}`~?”,

  5. A (potentially better) alternative to G-Force’s suggestion is to actually make a settings file for R specifically, so that you don’t turn periods in other languages (like Ruby, Python, Perl, etc.) into words, since they’re actually part of those languages’ syntax.

    Instead, with an R file open, go to Preferences > Settings – More > Syntax Specific – User. It will create a blank “R.sublime-settings” file where you can paste the code at https://gist.github.com/3081073.

    The new word boundaries will only work in R files, meaning that periods will be treated normally in other languages.

    1. I agree. I’m working on modifying the R and R Console syntax files to clean-up this and a couple of other issues (e.g., inappropriate syntax coloring in the console).

      1. just curious if you have a better R Console syntax? not sure why the one that comes with the package is odd (at least to me). i would prefer to just see the prompts, text input into the console, then output as 3 different colors.

        i’m kind of new to it all, so i haven’t figured out how to edit the syntax files to my liking. any hints? or, is your improved version available? fantastic post. new to all of this, but your post helped me get everything working. thanks!

      2. not sure if you’re still looking for an answer, but…
        the *REPL* console can be given any syntax, and you can use syntax-specific highlighting to color it however you want.

        the output is usually relatively simple compared to a language, so grabbing parts of another language’s syntax highlighting files can give you a lot of what you need. I’ve just been using python and it works fine. To set the syntax, go to view > syntax > and select the syntax you want. (I’m on a pc… I forget what it is on a mac but it’s similar)

        Alternatively, you can create your own syntaxes (http://stackoverflow.com/questions/15221150/custom-syntax-highlighting-in-sublime-text-2) and color schemes (e.g. http://tmtheme-editor.herokuapp.com/)

  6. Many thanks for this excellent guide. And thanks to they guys making this possible.

    I have one issue. I can use R fine with sublime. But I cannot load packages. (I can install them, but not load them), I get the error “[SublimeRepl: decode error]”?
    Any ideas?

    1. hhsievertsen-

      Hrm, no idea. I haven’t had any issues related to packages on my installations.

      To get some stuff out of the way, I imagine your installing and loading packages with:

      install.packages("ggplot2")
      library(ggplot2)

      This being an example of installing and loading ggplot2.

      If you continue to have problems, I’d recommend filing an issue at SublimeREPL’s github page. If I find a solution, I’ll post it here.

      1. Hi Tom,

        I found a solution. It was a quite stupid issue.
        The problem was that my system language is Danish. As a result R speaks Danish as well.
        When I load a package that requires other packages to be loaded, R writes a Danish word containing a special letter (“æ”), which causes the error above.
        I added a “LANGUAGE=en” option for R in the “Main.sublime-menu” file.
        What I did, is probably not the right solution. But it works. Do you have a better solution?

        Many thanks again!

  7. Tanks for the tip with “LANGUAGE=en”. I had the same problem with German.

  8. Thanks for the excellent post. Very helpful.

    Sublime supports Autocomplete for syntax in Python and Ruby for example – I haven’t found that feature for R yet – do you know how to enable it or where to find a plug in? I would like Sublime to autocomplete “write.csv” if I start typing wri…

  9. This is a great tutorial. I am trying to get the same functionality on a Mac and am having trouble. Specifically, I have installed the necessary packages and I have R running in SublimeText2, but I am unable to send code from one window to the R console. Whenever I type command + enter the R.app opens and the code is sent there. In other words the R console in the other window of sublimetext2 does nothing. If I switch to that console I can type in the same command and it works, however, I am unable to send it there. Any ideas?

  10. To get this working on my Mac I had to set PATH as “/usr/bin/r”

    Additionally to get the shortcuts working on my Mac I had to change “ctrl+X+Y” to “command+X+Y”

    Here is my keybinding file:

    [
    // Modified Sublime-REPL keybindings for an “R-friendly” set of shortcuts.
    // Copy and paste this text into the Key Bindings – User (under Preferences menu).
    // For more information, see http://tomschenkjr.net/2012/05/17/using-sublime-text-2-for-r/

    // Executes a selection of text in REPL, latter only displays code and does not execute
    { “keys”: [“command+shift+r”], “command”: “repl_transfer_current”, “args”: {“scope”: “selection”}},
    { “keys”: [“command+shift+r”, “r”], “command”: “repl_transfer_current”, “args”: {“scope”: “selection”, “action”:”view_write”}},

    // Executes the entire file (build) in REPL, latter only displays code and does not execute
    { “keys”: [“command + f7”], “command”: “repl_transfer_current”, “args”: {“scope”: “file”}},
    { “keys”: [“command + f7”, “r”], “command”: “repl_transfer_current”, “args”: {“scope”: “file”, “action”:”view_write”}},

    // Executes line(s) of text in REPL terminal, latter only displays code and does not execute
    { “keys”: [“command+alt+r”], “command”: “repl_transfer_current”, “args”: {“scope”: “lines”}},
    { “keys”: [“command+alt+r”, “r”], “command”: “repl_transfer_current”, “args”: {“scope”: “lines”, “action”:”view_write”}},

    // Executes a block (e.g., a custom function) of text in REPL terminal, latter only displays code and does not execute
    { “keys”: [“command+shift+alt+r”], “command”: “repl_transfer_current”, “args”: {“scope”: “block”}},
    { “keys”: [“command+shift+alt+r”, “r”], “command”: “repl_transfer_current”, “args”: {“scope”: “block”, “action”:”view_write”}}

    ]

    1. You can check to see if it’s an issue with keybindings or something else. First, check to see if your script file is either saved as a *.R file or simply set the syntax to R. Second, type in a simple command, keep the cursor on that line, then click Tools > SublimeREPL > Transfer to REPL > Lines. Let me know if that works.

      1. When you look at “Transfer to REPL”, what are the shortcut keys identified? “Alt + Shift + R, R”?

  11. Yes, for transfer line shortcut is “Alt + Shift + R, R”. I reinstalled Sublime and now it works, except transfer all file chortcut. It shows that I should press “Ctrl+Shift+,, f”. No idea what is wrong 🙂

    P.S. I edited Key Bindings file and changed ctrl+f7 to ctrl+shift+r+e. And now it works! But another weird thing that I have to press ctrl+shift+e, not ctrl+shift+r+e 🙂

    Thank you very much, Tom!

  12. Tom,

    Thanks so much for putting this intro together. It seems like Sublime will be much more powerful than Tinn-R. However, I am having trouble sending code to the R console. When I followed your advice to pro (Tools > SublimeREPL > Transfer to REPL > Lines), nothing happened. Any advice?

    1. I can transfer my code to the console but without auto execution..

      1. Hrm, not sure if I can diagnose. Any progress since initial post?

  13. Hi, and thanks for this tutorial !
    May Sublime Text work with R under linux environment ?

    1. It works under Linux too.
      just add the following line in your SublimeREPL user settings file.(Assuming R is already included in your PATH env variable.)
      {
      “default_extend_env”:{“PATH”:”{PATH}”}
      }

  14. Hello,
    I am wondering how you enabled the display of line numbers to the left of the code. I am using Windows 7, too. Thank you.

  15. Hi, Tom:
    ST2 has been upgraded to 2.0.2. It seems that sublimeREPL has to be upgraded as well.

  16. Hi, thanks for this tutorial and tips, this works better than any GUI! I experience a strange thing — i need to press all shortcuts twice. Why could this be?

    And also, when i press up arrow in the REPL console, it lists only those commands which i’ve typed directly in the console, or have transferred from a script using menu Tools -> SublimeREPL -> Transfer to REPL and then pressing Enter in the console. Could this be improved/fixed?

    Thank you again!

  17. Its a nice tutorial, thank you very much.
    One thing, the screenshots show that the R-console ist colorized, but I cannot find it so on Ubuntu 12.04 with sublime3

    Any idea?
    Thanks

    1. The colorized text? You can choose the syntax so the text will be formatted based on the text you use. You can choose the syntax by selecting View > Syntax

      1. Oh yes, Thanks,

        But another question is: Is there a possibility to call r-help with this? For example with a macro which calls help(“xxxx”)?

  18. I’m trying to use the key binidngs provided here, but repeatedly getting this error message:
    Error trying to parse file: Expected value in ~/Library/Application Support/Sublime Text 2/Packages/User/Default (OSX).sublime-keymap:3:32

    1. It seems like something is missing from the article. It says “Now you have told where Sublime Text can look to find R,” but I can’t find or see the example that shows how to do that. Did something get accidentally deleted from the article?

  19. Thank you for this great tutorial! I got it working on a mac too, thanks to @slayton!

    I would like to follow-up on a question asked by Stas Malavin on August 8, 2013:

    “I experience a strange thing — i need to press all shortcuts twice. Why could this be?”

  20. I’m not sure why it needs to be pressed twice, I also experienced* the same thing.

    *I should note that, while I still use SublimeText, my principal R programming is now done out of RStudio.

  21. Thanks for the tutorial!

    `help()` command works in console, but result is displayed in console also. Is there any way to have separate window opened with the result? Ideally like it works in standard R console – with active URLs.

    1. if you are on a mac, what i’ve been doing is using an app called “Dash” (available from the mac app store, free but must pay to remove a time delay) and a sublime package called “DashDoc” – with that, i just hit control-h on a word i want the help for, and it near instantly opens up the R documentation in the Dash app.

      only minus at the moment is, i have to figure out how to make Dash documentation for any non-default R packages i use. their instructions are not very new-programmer friendly, and look quite complicated (to me).

  22. Thanks for the useful comments. When I write a new R script it fails to read files in the SAME directory with the error:

    Error in file(file, “rt”) : cannot open the connection

    I checked getwd() and it shows “C:/windows/system32” which is probably the directory where sublime text is installed.

    Is there a way to set the current working directory to the location of the current file. This can be easily done in RStudio with Session > setwd > source file location.

    Any help would be greatly appreciated.

    1. Likely, the best way is to use the setwd() command and manually set it to the preferred directory (e.g., setwd(“C:\Users\username\R-files\project”)). There isn’t any way to do it with a GUI.

      1. Thanks Tom. I understand there is no way to do this using the GUI with sublime text, but I was wondering if there is a way to read the directory of the active file and set the current working directory to that.

        If this is not possible through user preferences etc., can I at least programmatically read the location of time active file and pass that as a parameter to setwd() in R? Any help would be great.

        Hardcoding the setwd() might not be compatible across platforms and therefore I am hesitant to do that.

      2. Ah, ok, that does help clarify and understand the issue of hard coding if you intend the R scripts to be ran on multiple computers.

        Conducted a cursory search and found this answer that is applicable to Sublime Text.

  23. Perhaps a silly question: when using the repl for a few minutes, the prompt is way at the bottom of the document, which is a bit awkward. Anyway to keep a margin below the prompt?

  24. Would you happen to have experience troubleshooting installation on OS X El Capitan? I get the following error when I start R from within ST2

    “SublimeREPL: obtaining sane environment failed in getenv()
    Check console and ‘getenv_command’ setting
    WARN: Falling back to SublimeText environment”

  25. Thank you so much for this wonderful tutorial. I especially love the ctrl+shift+r shortcut.

    However, I notice that when I use ctrl+shift+r (after pasting your code into the user keybind preferences), I have to press another button to make the shortcut actually send and execute the line/selection of R code; if I just do ctrl+shift+r, nothing actually happens. This “extra button” seems to be anything from the space bar to arrow keys (except “r”, which is another shortcut, as you know). Is there a way to eliminate this additional step?

    1. I was able to get around this problem by commenting out the ctrl+shift+r, r line

  26. Print is becomes really slow when using the REPL (compared with just the R Gui). It gets the point that I cannot use the REPL. Since you mentioned that your work become slow as well, I was wondering if you found a solution or cause for this problem? Thanks.

  27. Hola Tom and thanks for this great tutorial. I have been working with ST3 and RStudio for a while, and it simplifies my workflow (and my life). One question: how can i execute the ctrl+L command to clear the console?
    Thanks in advance.

    1. That’s a command specific to the R console (and RStudio), but I don’t think it applies to Sublime Text.

  28. Thank you Tom for the great tutorial!
    But despite following your steps word by word, I still cannot have the intended shortcuts working in my ST3. Rarely, I get the output, like 1 out of 20 times. For the rest, I am just left with pressing Ctrl+Shift+R or the rest of the shortcuts endlessly, and nothing happens.

    Please help me out! I do not want to shift to Notepad++ due to this issue!

    1. Hi GanJin-

      I have not tested this at all with ST3, so I cannot guarantee that it would work. I’m still using ST2 (as RStudio is becoming more prominent in my R workflow), so not sure where it would potentially break.

  29. Pingback: Link posjitu app download

Leave a Reply to Tom Cancel reply