Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 806
Nathan Basanese Avatar asked Feb 04 '17 22:02

Nathan Basanese


People also ask

How do I run an R script from the R console?

To execute your code in the R script, you can either highlight the code and click on Run, or you can highlight the code and press CTRL + Enter on your keyboard. If you prefer, you can enter code directly in the Console Window and click Enter.

How do I run an R script in RStudio?

To execute the line of source code where the cursor currently resides you press the Ctrl+Enter key (or use the Run toolbar button): After executing the line of code, RStudio automatically advances the cursor to the next line.

How do I run an R code in line by line?

On your keyboard: press CTRL+ENTER . The line will be executed, the cursor jumps into the next line. Again, press CTRL+ENTER to execute the next line … and so far, and so on.


1 Answers

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

like image 78
Nathan Basanese Avatar answered Sep 30 '22 19:09

Nathan Basanese