Categories
Projects

R Error: unexpected input in “{“

I’ve been using R lately to help look at some greenhouse data at the Grow Haus. The Grow Haus is a great space filled with good energy and people on a mission to provide sustainable food production, distribution, and education. And good people need good data.

So, I was crushed when my formerly working script to read a .csv file into R and graph that data stopped working. For reference, I am working on a MacBook Pro running OSX (10.6.8) and running R version 3.0.1. I kept getting Error: unexpected input in “{“ when I ran it from the terminal command line using Rscript file.r.  It worked last week. What gives?

I first tested each individual line of the script in the R console, and they all worked. This was originally more frustrating, but then I figured it was a communication problem and decided to run R through the terminal. To start R from the command line instead of just in the console, type R. To load a script into R, use source(‘file.r’). I got the same error again.

So I opened the file in the terminal using vi file.r. This showed me that when I had last saved the file in TextEdit, it had switched from plain text to rich text format and injected a bunch of junk as a header that was preventing R from reading the script. I switched it back to plain text in TextEdit (Format< Make Plain Text) and set the Open and Save preferences to use Plain Text Encoding (UTF-8) when opening or saving files. Then the script magically worked again. Boo to text editors switching stealthily to .rtf mode! Maybe this will be a nudge to get more comfortable using a terminal text editor.

Some bonus R data checking tips: After running source(‘file.r’), ls() will list the loaded variables in your workspace. If you have a table loaded called data, you can see the header and first could rows using head(data).

What do you think?