I have been experiencing the same problem, and have found that it is caused by a bug in RStudio (the code runs fine in R and R-gui, but fails in RStudio.) It is hard to reproduce until something gets corrupted in RStudio's saved state, after which the behaviour is pretty consistent.
Removing ~/.rstudio-desktop
fixed the issue for me.
mv ~/.rstudio-desktop ~/rstudio-desktop.old
More on resetting RStudio's state on various platforms here.