Skip to Main Content

R

Program Conventions

Most common way to have a record of your analysis is to use R Script file. A ".R" script file is where you write code to run procedures and/or commands to analyze or manipulate data.

Opening a blank .R file can be done on the main window of RStudio. To start, open RStudio on your computer and in the upper left corner of the window click:

  1. File
  2. New File
  3. R Script  

And, you can begin writing code. You can also open a new R script by "control + shift + N".  

As you can see, R can work with other kinds of files like Quarto, Markdown, CSS, Python, SQL, and many others.

To save a .R file, click on the floppy disk icon highlighted in the red circle.

 

undefined

You can also use the "Ctrl + S" shortcut on Windows or the "Cmd + S" shortcut on Mac.

We can think of a .R file as a ‘live’ word document, where we write commands that tell RStudio what to do with our data from descriptive statistics to regression models.

RStudio code is written with commands which are the main function or analysis you want RStudio to do in a line of code.

By starting a line with a “ # “, we can write notes and comments that will appear green. RStudio does not recognize this as code.

 

You can also write blocks of text that do not appear as code by also starting the text with a " # ".

And, if you put four dashes after your code, the line automatically becomes a heading. You can see these headings from the outline bar.

To run code, that is to tell RStudio what you want to do, highlight the code you want to run and click on the 'Run' button highlighted in red below. You can also use keyboard shorts like Ctrl+Enter or Alt+Enter on a Windows keyboard (use Cmd + Return).

In R, the primary assignment operator is <-, used to assign values to variables. Assignment operator helps us to create new objects, which can be new variables, figures, dataframes, and many more!

While the equals sign (=) can also assign values, <- is preferred for clarity and consistency, particularly in object-oriented programming. Using <- makes code easier to read and aligns with R's conventions, ensuring better understanding and maintenance of your scripts.

Example