Search code examples
open-sourcerstudio

How do I run an R script from within RStudio's built-in R console?


I'm assuming it's like Python's import statement, but I'd like a quick answer, since I'm in the middle of an introduction class right now.

This was the closest I got, but it didn't seem to match the question, as it shows how to run an R Script from the system CLI, not the blue RStudio > prompt:

Run an R-script from command line and store results in subdirectory


Solution

  • Short Answer using source() function

    Once you download, install, and open the RStudio, you'll see a part in the lower left with blue greater than symbols >.

    In the part of RStudio's GUI with the blue >, enter the following

    > setwd('/folder/where/the/file/is/')
    > source('file_name')`
    ...output, if any, appears below...
    

    Example:

    Let's assume I have a file at /home/myusername/prj/r/learn_r/insurance_data.r that I want to run.

    I would start up RStudio, and enter the following in the little window it has labeled Console:

    Remember, it's setwd, not setpwd

    Remember the quotation marks! Don't be silly like me.


    Annoyingly long answer with screenshots using source() function

    Well, it turned out to be much simpler than I expected to run this from RStudio's built-in console. I was surprised that this had not already been asked about RStudio, before. If it has, I guess I'll have a burned question.

    Anyway, a little trial and error showed me how to do this:

    enter image description here

    Yay, output has appeared below.

    Make sure to set your working directory, first.

    I did this as follows from inside RStudio 1.0.143 on my Ubuntu 16.04 LTS environment:

    setwd("~/proj/r/learn_r")
    

    enter image description here

    Next, you can enter help(source), you can search for the syntax of the source() function, and you can just type it in to the RStudio console for a prompt:

    enter image description here