Introduction to R programming

Introduction to R and Rstudio and how to install it onto your machine and some basic statements
Author

Mugabi Trevor .L

Published

2024-09-02

Keywords

R and Rstudio, Installation, Windows installation, Linux installation, macOS installation, Rstudio installation, Rstudio GUI

Introduction to R Programming

Welcome to this R programming tutorial! R is a powerful tool for statistical analysis and data science, and best of all—it’s free and open-source.

Built with statisticians and data scientists in mind, R is ideal for statistical computing, data analysis, and handling large datasets. It’s cross-platform, running on Windows, macOS, and Linux, and can be integrated with big data tools like Hadoop and databases.

One of R’s strengths is data visualization. Whether you need static or interactive visualizations, R provides extensive customization through packages like ggplot2 and plotly. Plus, CRAN (the Comprehensive R Archive Network) offers over 18,000 packages, expanding R’s capabilities.

With a strong, active community, you’ll find plenty of support as you explore R’s features. So, let’s dive in and see what R can do!

Installing R and RStudio

To get started, you’ll need to install R, which sets up the language on your computer. However, for coding and managing your projects, we recommend using RStudio, a popular IDE designed for R.

The R is freely available for Windows, Mac and Linux operating systems from the Comprehensive R Archive Network (CRAN) website and R studio is available free for download at Rstudio-desktop

Make your way to the Comprehensive R Archive Network (CRAN) website and you will be greeted with the following page below

Cran home page

Choose the operating system that your using or your planning to install R on and follow along as below

1. Windows installation

Assuming you have made you way to the Comprehensive R Archive Network (CRAN) website.

Select the “Download R for windows option” as shown by the Arrow below in the image

Select windows option from Cran page

After making the above selection, you will be brought to the next page below. Now click on “install R for the first time” which will take you to the next page.

select windows base for the first time

This show be on your screen as shown below, all thats left to do is click on “Download R for Windows”, This should start your download of R.

Select a path to where you would like to download your R install exe

Please keep in mind to install an R version compatible with your system

Download R

After the download is complete you can browse to your downloads and find the R.exe downloaded file and open it to run it as seen in the images below

Downloaded R_exe in downloads

After it has launched, select your preferred language, accept the terms and conditions and follow the rest of the instructions given by the installer

launched R_exe

NOTE: i would recommend you leave the default R set path to prevent any issues that may arise if your change the installation directory

default dir

2. macOS installation

Assuming you have made you way to the Comprehensive R Archive Network (CRAN) website.

To install R on macOS, follow these steps:

  1. Download the R Installer:

  2. Install R:

    • Once the download is complete, open the .pkg file.
    • Follow the installation instructions to complete the process.
  3. Verify the Installation:

    • Open the Terminal and type:

      R --version
    • This will display the installed R version, confirming the installation was successful.

3. Linux installation

Assuming you have made you way to the Comprehensive R Archive Network (CRAN) website.

To install R on a Linux distribution like Ubuntu, follow these steps:

  1. Update the Package List:

    Open your terminal and run

    sudo apt-get update
  2. Install the base R system using the following command:

sudo apt-get install r-base
  1. Verify the Installation:

    R --version

Installing Rstudio

Installing RStudio on Linux, macOS, and Windows

After installing R, you can install RStudio, an Integrated Development Environment (IDE) for R. Follow the steps for your specific operating system. The website Auto detects your system and offers you the right package for your machine

1. Installing RStudio on Linux

  • Download RStudio :

    Rstudio home page

    • Scroll down to the RStudio Desktop section and select the version for Linux (e.g., .deb or .rpm file).
  • Install RStudio:

    • For Ubuntu or Debian-based distributions, use:

      sudo dpkg -i rstudio-x.y.z-amd64.deb

      Replace x.y.z with the version number you downloaded.

    • For Red Hat or Fedora-based distributions, use:

      sudo yum install rstudio-x.y.z-x86_64.rpm
  • Launch RStudio:

    • Open RStudio from the terminal by typing rstudio, or find it in your application menu.

2. Installing RStudio on macOS

  • Download RStudio:

  • Install RStudio:

    • Open the downloaded .dmg file.
    • Drag the RStudio icon into your Applications folder.
  • Launch RStudio:

    • Go to your Applications folder and double-click on the RStudio icon to start.

3. Installing RStudio on Windows

  • Download RStudio:

  • Install RStudio:

    • Run the downloaded .exe file.
    • Follow the installation instructions to complete the setup.
  • Launch RStudio:

    • After installation, you can find RStudio in your Start Menu. Click to open it.

You’re now ready to start coding in R with RStudio!

4. Displaying Output

Given the example code below,if you copy it and paste it into the scripting area as shown in the image above and press Run or hold Control + Return keys. it will show you the out put in the console area as shown the image above.. expect your output there

print("Welcome to R programming")
[1] "Welcome to R programming"

5. Basic Statements

Well to start you off with the basics the first program by tradition in any programming language to write is the print("Hello world") but i think we live in modern times you can print whatever we want.Wait whats that? what does the print() function do?, well it prints out to the console whatever is passed into it as an argument.thats to say i could say any of these below and it would print them out.

print("How many programmers does it take to change a light bulb? None. It’s a hardware problem!")

print(" Why do programmers prefer dark mode? Because light attracts bugs!")

print("Why do Java developers wear glasses? Because they don’t see sharp!")

print("Why did the statistician bring a ladder to the bar? Because they heard the drinks were on the house!")

Lets give all the above a try below and see the output.

print("How many programmers does it take to change a light bulb? None. It’s a hardware problem!")
[1] "How many programmers does it take to change a light bulb? None. It’s a hardware problem!"
print(" Why do programmers prefer dark mode? Because light attracts bugs!")
[1] " Why do programmers prefer dark mode? Because light attracts bugs!"
print("Why do Java developers wear glasses? Because they don’t see sharp!")
[1] "Why do Java developers wear glasses? Because they don’t see sharp!"
print("Why did the statistician bring a ladder to the bar? Because they heard the drinks were on the house!")
[1] "Why did the statistician bring a ladder to the bar? Because they heard the drinks were on the house!"
print("Why did the statistician bring a ladder to the bar? Because they heard the drinks were on the house!")
[1] "Why did the statistician bring a ladder to the bar? Because they heard the drinks were on the house!"

I guess you now know what the print() function does and what an argument is. its whatever you input into the function

6. Syntax and Structure

R is a powerful language for statistical computing and graphics. Understanding its basic syntax and structure will help you get started with writing and running R code effectively.

1. Variables in R are created using the <- operator or = operator. R is case-sensitive.

x <- 10  # Using the <- operator
y = 20    # Using the = operator

2. Data Types

R supports several data types Numeric: Represents real numbers Integer: Represents whole numbers (use L suffix). Character: Represents text. Logical: Represents boolean values (TRUE or FALSE).

# This is a numeric
num <- 3.14 
print(num)
# This is an int
int_num <- 42L 
print(int_num)
# This is a character
text <- "Hello, R!"
print(text) 
# this is a logical 
flag <- TRUE
print(flag)
[1] 3.14
[1] 42
[1] "Hello, R!"
[1] TRUE

3. Basic Math Operations

R supports standard mathematical operations: Let x be 2 and y be 4.

# Assigning the values.
x <- 2
y <- 4

Addition: +

# adding x and y
sum <- x + y
print(sum)
[1] 6

Subtraction: -

# getting there difference
difference <- x - y
print(difference)
[1] -2

Multiplication: *

# getting there product
product <- x * y
print(product)
[1] 8

Division: /

# dividing the two numbers
quotient <- x / y
print(quotient)
[1] 0.5

Exponentiation: ^

# raising x to the exponent of 2
power <- x ^ 2
print(power)
[1] 4

Modulus: %% (remainder after division)

# finding the remainder for the divison of x by y
remainder <- x %% y
print(remainder)
[1] 2

7. Comments

To write a comment in R programming we using the hash sign “#”. “what’s a comment i hear My soon to be R Wizard!” Well a comment is a way to tell R to ignore some input and not treat it as code. We use comments to leave our selves bread crumbs to follow in the future that explain exactly what assumptions were taken or what the code does.

Commenting is a very important part of R wizarding. You need to leave comments for yourself and maybe your team mates to read and understand what’s going on or why your did something in the code

Take a look at the examples below

# This is a comment my young R wizard it wont be run but ignored and no output will be returned if the cell is run
# you can also use comments to document as below 
# Me summoning my R powers below
print("I the R wizard of R lang, call upon the print func.")
# YES YEs yes yessss do you fill the power fo comments yet
[1] "I the R wizard of R lang, call upon the print func."

8. Exercise

Objective: Get hands-on practice with comments, variables, data types, and basic math operations in R.

  • Instructions:
    • Create three variables: a, b, and c. 
    • Print the results of each operation using the print() function.
    • Include a descriptive comment before each operation to explain what it does.
  1. Assign the following values to them:
    • a: 10 (Numeric)
    • b: 3.5 (Numeric)
    • c: “R Programming” (Character)
  2. Compute the following operations using the variables:
    • Addition of a and b
    • Subtraction of b from a
    • Multiplication of a and b
    • Division of a by b
    • Exponentiation of b raised to the power of a
    • Print Results