Lesson Objectives

At the end of the lesson, the students are expected to:

  • install R and RStudio to their personal computers,
  • customize the appearance and set up of their RStudio,
  • perform basic calculations in R, and
  • create and assign values to variables in R.

What is R and Why use R?

  • R is a scripting language.

  • Used widely for statistical data manipulation and analysis.

  • R has become popular because it’s free and people can contribute to the development of R.

  • R is the defacto standard among professional statisticians.

  • comparable, and often superior, in power to commercial products.

  • available for Windows, Mac, Linux.

  • in addition to enabling statistical operations, it’s a general programming language, so that you can automate your analyses and create new functions.

  • object-oriented and functional programming structure.

  • it’s easy to get help from the user community, and lots of new functions get contributed by users, many of which are prominent statisticians.

  • it has a feature that supports the use of other programming languages, such as Python and the like.

  • it has a feature for reproducible research.

Installing R and R Studio

To install R

  1. Open an internet browser and go to www.r-project.org

  2. Click the “download R” link in the middle of the page under “Getting Started.”

  3. Select a CRAN location (a mirror site) and click the corresponding link.Look for the Philippines.

  4. Click on the “Download R for Windows” link if you are using Windows. Otherwise, Click on the “Download R for (Mac) OS X” or “Download R for linux”.

  5. Click “base”.

  6. Click “Download R 4.0.2 for Windows”.

Note that R is constantly being updated and so new version will be available from time to time. It is possible that when you navigate to the website page, by default, you will see the latest version.Download the latest version of R.

  1. Double-click the downloaded file to open, and follow the installation instructions.

  2. Now that R is installed, you need to download and install RStudio.

R Studio

RStudio is an integrated development environment (IDE) for R. It includes a console, syntax-highlighting editor that supports direct code execution, as well as tools for plotting, history, debugging and workspace management. Click here to see more RStudio features.

For ease of use, navigation and computation, we will be using R Studio throughout our lessons.

To Install R Studio

  1. Go to RStudio

  2. Click on “Products”.

  3. Under Open Source, click “RStudio”.

  4. Scroll down the page, and click RStudio Desktop.

  5. Choose the open source edition which is free.

  6. Click on the version recommended for your system.

The RStudio Interface

To get started with using R Studio, open your RStudio. You will see the following R Studio interface where the window is partitioned into four major panes.

Figure 1

RStudio RStudio is a four pane work-space for

  1. creating file containing R script,

  2. typing R commands,

  3. viewing command histories,

  4. viewing plots and more.

Code editor allows you to create and open a file containing R script. The R script is where you keep a record of your work. R script can be created as follow: File –> New –> R Script.

R console is for typing R commands.

Environment Pane: shows the list of R objects you created during your R session.

  • Import Dataset tab allows you to load datasets stored in your computer in the R environment.

History Pane: shows the history of all previous commands

Connections Pane shows you all the connections you have made to supported data sources, and lets you know which connections are currently active.

Tutorial Pane is powered by the learnr package which hosts the tutorials of the use of different packages.

Files tab: show files in your working directory Plots tab: show the history of plots you created. From this tab, you can export a plot to a PDF or an image files. Packages tab: show external R packages available on your system. If checked, the package is loaded in R.

Customizing RStudio

To change the appearance of RStudio: Tools > Global Options > Appearance

You can use the Global options to customize the Code, Pane layout and other parts of RStudio. Take time to explore.

For more info about RStudio read the Online Documentation.

R Working Directory

Recall that, the working directory is a folder where R reads and saves files.

Check your existing working directory

To check your existing working directory: Type getwd() in the R Console and press enter.

getwd()
## [1] "C:/Users/Roel Ceballos/Dropbox/Lecture/Foundations of Computer Programming/R Programming"

Change your working directory

From RStudio, use the menu to change your working directory under Session > Set Working Directory > Choose Directory.

Easy R Programming Basics

R can be used to perform calculations. For a start, we have the basic arithmetic operators:

  • addition (+)
  • subtraction (-)
  • mutiplication (*)
  • division (/)
  • exponentiation
# addition
3+7
## [1] 10
#subtraction
7-3
## [1] 4
#multiplication
7*3
## [1] 21
#division
8/2
## [1] 4
# exponentiation
7^2
## [1] 49

Basic arithmetic functions

Logarithms and Exponentials:

log2(x) # logarithms base 2 of x
log10(x) # logaritms base 10 of x
exp(x) # Exponential of x

Trigonometric functions:

cos(x) # Cosine of x
sin(x) # Sine of x
tan(x) #Tangent of x
acos(x) # arc-cosine of x
asin(x) # arc-sine of x
atan(x) #arc-tangent of x

CRAN Resources for R Programming

  • Almost all mathematical operations and functions can be found in R, meaning you don’t have to create them from scratch. All you have to do is call them and input the right argument of the function.

  • The base package, which is loaded when you install R, contains the most commonly use of these math functions. Some useful built-in functions can be found here.

  • On the other hand, advanced mathematical and statistical functions such as those that are used in Time series analysis, Differential equations, Optimization, and Mathematical Modelling can be found in other R packages that you can easily install and use.

  • CRAN which stands for Comprehensive R Archive Network has created Task Views for these advanced mathematical and statistical operations that may serve as a guide for users. For instance, you may click on the hyperlink below to check these Task Views.

Assigning values to Variables

A variable can be used to store a value.

For example, the R code below will store the price of a lemon in a variable, say “lemon_price”:

# Price of a lemon = 2 euros
lemon_price <- 2
# or use this
lemon_price = 2

Note that it’s possible to use <- or = for variable assignments.

Note that R is case-sensitive. This means that lemon_price is different from Lemon_Price.

To print the value of the created object, just type its name:

lemon_price
## [1] 2

or use the function print():

print(lemon_price)
## [1] 2

R saves the object lemon_price (also known as a variable) in memory. It’s possible to make some operations with it.

# Multiply lemon price by 5
5 * lemon_price
## [1] 10

You can change the value of the object:

# Change the value
lemon_price <- 5
# Print again
lemon_price
## [1] 5

The following R code creates two variables holding the width and the height of a rectangle. These two variables will be used to compute the area of the rectangle.

# Rectangle height
height <- 10
# rectangle width
width <- 5
# compute rectangle area
area <- height*width
print(area)
## [1] 50

The function ls() can be used to see the list of objects we have created:

ls()
## [1] "area"        "height"      "lemon_price" "width"

Note that, each variable takes some place in the computer memory. If you work on a big project, it’s good to clean up your workspace.

To remove a variable, use the function rm():

# Remove height and width variable
rm(height, width)
# Display the remaining variables
ls()
## [1] "area"        "lemon_price"