Using R and BBEdit

The statistical programming environment R is very powerful. The Mac text editor BBEdit is also very powerful. Together they are the ultimate combination. Luckily, with minimal effort you can make them very happy bedfellows. Here are two ways of integrating R with BBEdit.

Syntax colouring
Download the R syntax colouring file and move it to your “~/Library/Application Support/BBEdit/Language Modules/” folder.

Running code from within BBEdit
Two AppleScripts based on a post on an R mailing list. The first script will run the current selection (or line if there is no selection) in R. The second script will run the entire file in R. Save these scripts into your “~/Library/Application Support/BBEdit/Scripts/” folder. You can then go to Window -> Palettes -> Scripts and assign some shortcut keys to these scripts. I use Command-R to run the file, and Command-Option-R to run the line.

Open up Applescript Editor and paste these chunks of code into two separate files.

Save this file as ‘Run file in R’:

tell application "BBEdit"
   set theFile to (file of document of front window as string)
   set theFilePath to POSIX path of theFile
end tell

tell application "R"
   if theFile is "missing value" then
      cmd "print(" & quote & "Error: BBEdit file is not saved" & quote & ")"
      cmd "source(" & quote & theFilePath & quote & ")"
   end if
end tell

Save this file as ‘Run line in R’:

tell application "BBEdit"
    set theText to (selection of front window as string)
    if (theText) is "" then
        set theText to line (get startLine of selection) of front window as string
    end if
end tell

tell application "R"
    cmd theText
end tell

Jonathan Marc Bearak has some similar tips on his R & BBEdit integration page.

One thought on “Using R and BBEdit

Leave a Reply

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