Introduction to
R & RStudio

Dr. Ajay Kumar Koli, PhD

  • Founder & Director of SARA
  • JNU, Pondicherry Central University, University of Hyderabad, University of Würzbürg
  • Pursuing MSc Data Science from IGNOU

Data Science Project


The R Programming Language



“R is a free software environment for statistical computing and graphics.”

🥳 Latest Ranking of R

Rank #8 in May 2026: Highest Position (since 2007)

History of R

  • Intially as S language by Bell Labs.

  • First appeared in August 1993 as R language by:

Ross Ihaka, New Zealand Statistician

Robert Gentleman, Canadian Statistician

Download R from CRAN

Demo: https://www.r-project.org/

R Console

  • R version 4.6.0 (2026-04-24)

  • R name “Because it was There”

  • R licence “ABSOLUTELY NO WARRANTY”

  • R prompt >

Workspace Image


Don’t save workspace image

  • It helps in “freshly minted R sessions”.

  • “put more trust in your script than in your memory”.

R Coding

Ways to Run R code

  • Type code directly after the > prompt and press Enter to run
  • Best for quick, one-line commands and experimenting
  • Output appears immediately below your command
  • Nothing is saved - closing R loses everything you typed
  • Think of it as a scratch pad
  • Write multiple lines of code in a plain text file saved as .R
  • Code is saved and reusable - you can share it with others
  • Output appears in the Console, plots appear in the Plots pane
  • Mix R code chunks with text, headings, and images in one document
  • Click Render to produce a final HTML, PDF, or Word report
  • Perfect for reproducible research and sharing your full analysis as a report

R Console


Code

7

Output

[1] 7

Press Enter key to run the code in console

Copy code to clipboard

R Console: Addition


Code

2 + 1

Output

[1] 3

Operators


12 + 3 in this code + is an operator.


“Operators are used to perform operations on variables and values.

Arithmetic Operators

“Arithmetic operators are used with numeric values to perform common mathematical operations.”

  • Put spaces between and around operators (= + - * /)

  • Increase screen font size for better view.

Arithmetic Operators


Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
^ Exponent x ^ y
%% Remainder x %% y

R Console: Subtraction


Code

10 - 2

Output

[1] 8

R Console: Multiplication


Code

12 * 4

Output

[1] 48

R Console: Division


Code

25 / 5

Output

[1] 5

R Console


Code

3434 + 343453 * 2323 / 534 - 1000

Output

[1] 1496519

R follows the BODMAS (bracket, order, division, multiplication, addition and subtraction) rule to solve mathematical equations.

R Comparison Operators


“Comparison operators are used to compare two values.”

R Comparison Operators


Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

R Console


Code

4 == 5

Output

[1] FALSE

R Console


Code

67 > 60

Output

[1] TRUE

R Miscellaneous Operator

“Miscellaneous operators are used to manipulate data.”


Code

12:36

Output

 [1] 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

What if we want to add all these values in R?


 [1] 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

R Functions

R Function

A function is a shortcut for a task we do repeatedly.

“A function, in a programming environment, is a set of instructions.”

R Function sum()

sum(2, 4, 6)
[1] 12

Structure of a R function


Structure of a R function


Structure of a R function


Structure of a R function


Structure of a R function


R Function sum()

sum(12:36)
[1] 600

Round function

Function with default argument.

round(x = 42.58756)

or

round(42.58756)
[1] 43

or

[1] 43

Round function

Function with a specific value of an argument.

round(x = 46.58754, digits = 2)

or

round(46.58754, 2)
[1] 46.59

or

[1] 46.59

Square Root Function

Function with a specific value of an argument.

sqrt(x = 9)
[1] 3

Sequence Function

Function with a specific value of an argument.

seq.int(from = 10, to = 30, by = 5)

or

seq.int(10, 30, 5)
[1] 10 15 20 25 30

or

or

[1] 10 15 20 25 30

Plot using R

plot(1:100)

Getting Help with R

  • The help() function and ? help operator in R.

  • Use args() function to the get the list of arguments of a function.

Your Turn

  • Add two numbers: 15 + 27

  • Create a sequence of numbers from 1 to 10

  • Create a sequence from 5 to 50, interval by 5

  • Find the square root of 81

  • Round the number 3.786 to 2 decimal places

Answers

  • Add two numbers: 15 + 27, 15 + 27

  • Create a sequence of numbers from 1 to 10, seq(1, 10)

  • Create a sequence from 5 to 50, interval of 5, seq(5, 50, by = 5)

  • Find the square root of 81, sqrt(81)

  • Round the number 3.786 to 2 decimal places, round(3.786, 2)

😏 That’s okay but how to …

  • Everything in one Software codes, results, writing.

  • Always reproducible re-run work, anytime, by anyone.

  • Share and publish with other Word, PDF or HTML.

We need a superhero 🐾 RStudio

RStudio IDE




RStudio is an integrated development environment (IDE) for R and Python from company posit

R and RStudio


Imagine R as a powerful engine


and RStudio as a stylish car


RStudio IDE

RStudio \(\rightarrow\) Tools \(\rightarrow\) Global Options

RStudio \(\rightarrow\) Tools \(\rightarrow\) Global Options

RStudio Without Project

RStudio Without Project

RStudio Project Helps:

“to divide your work into multiple contexts, each with their own”

  • Working directory,
  • Workspace,
  • History, and
  • Source documents.

Create RStudio project

Create RStudio project

In case anything goes wrong\(...\)

Create RStudio Project

Create RStudio project

Create RStudio project

Create RStudio project

Create RStudio project

RStudio project “name”

RStudio project “path”

RStudio project

Your Turn

Run these codes in the console of RStudio

  • “Hello World”
  • 12 + 2
  • 3 * 9
  • 34 == 34
  • 67 == 90

R Script

Pros of R Script (.R File)

  • Clean and focused - a .R file contains only code, making it easy to read, edit, and run without any extra formatting.

  • Fast to execute - you can run the entire script in one go, making it ideal data cleaning scripts, and automation.

  • Easy to share and version control - a plain .R file is lightweight and it opens immediately.

Create R Script

How to use this file

  • Run one line at a time: place cursor on a line: Ctrl + Enter (Win) / Cmd + Enter (Mac)
  • Run a whole section: select lines → Ctrl + Enter
  • Run the full file: Ctrl + Shift + Enter
  • Output appears in the Console

Variables & Data Types

  • A variable stores a value, like a box, so you can reuse it.

  • Use <- to assign (R’s way of saying “equals”): Alt + - (Win) / option + - (Mac)

  • Character (text - always in quotes), numeric (whole number or decimal) and logical (TRUE or FALSE)

Create Variables

name <- "SARA Institute" # character

year <- 2023 # numeric

fee <- 4500.00 # numeric

is_free <- FALSE # logical

Comment is any line in R that starts with # - R completely ignores it when running code

Type of a Variable

Type variable name and run

Code

class(name)

class(year)

class(fee)

class(is_free)

Output

[1] "character"
[1] "numeric"
[1] "numeric"
[1] "logical"

See a quick Summary of Variable

Code

str(name)

str(year)

Output

 chr "SARA Institute"
 num 2023

Your Turn

  1. Create a variable called my_name with your name.

  2. Create a variable called my_city with your city.

  3. Print both. What class are they?

Beautiful R Codes

  • Writing readable code because other people might need to use your code.

  • Writing readable code because you might need to use your code, a few weeks/months/years after you’ve written it.

  • Put spaces between and around variable names and operators (= + - * /).

  • Break up long lines of code.

  • Keeping a consistent style.

Vector

  • A vector is a sequence of values of the SAME type.

  • c() function means “combine” - it is how to build a vector.

students <- c("Priya", "Rahul", "Anita", "Suresh", "Meena")

scores <- c(88, 75, 92, 60, 85)

passed <- c(TRUE, TRUE, TRUE, FALSE, TRUE)

Access Individual Elements

R starts counting from 1

Code

# first student
students[1]

# third score
scores[3]

# elements 2 to 4
students[2:4]

# elements 1 and 5
scores[c(1, 5)]

Output

[1] "Priya"
[1] 92
[1] "Rahul"  "Anita"  "Suresh"
[1] 88 85

Arithmetic on Vector

Code

# add 5 bonus marks to everyone
scores + 5

# increase all scores by 10%
scores * 1.1

# TRUE/FALSE — who scored 70 or above?
scores >= 70

Output

[1] 93 80 97 65 90
[1]  96.8  82.5 101.2  66.0  93.5
[1]  TRUE  TRUE  TRUE FALSE  TRUE

Built-in Summary Functions

  • length(scores) for how many elements?
  • sum(scores) for total
  • mean(scores) for average
  • median(scores) for middle value
  • max(scores) for highest
  • min(scores) for lowest
  • range(scores) for min and max together
  • sd(scores)for standard deviation

Cons of R Script (.R File)

  • Output is not saved with the code - plots appear in the Plots pane and results in the Console, but closing RStudio loses everything; you have to rerun the script every time to see the output again.

  • No narrative or context - you can only add short comments with #; there is no space to explain your thinking, interpret results, or present findings in a readable way for others.

  • Not reproducible as a report — a .R file cannot be directly shared as a document; turning your analysis into something a non-coder can read requires extra steps, unlike .qmd which renders everything in one click.

Your Turn

  1. Create a vector of 5 temperatures (any values you like).

  2. Find the mean, max, and min.

  3. Which temperatures are above 30? (use >= 30)

Data Frames

Data Frame

participants <- data.frame(
  name = c("Priya", "Rahul", "Anita", "Suresh", "Meena"),
  city = c("Delhi", "Jaipur", "Mumbai", "Lucknow", "Pune"),
  score = c(88, 75, 92, 60, 85),
  passed = c(TRUE, TRUE, TRUE, FALSE, TRUE)
)

# print the whole table
participants
    name    city score passed
1  Priya   Delhi    88   TRUE
2  Rahul  Jaipur    75   TRUE
3  Anita  Mumbai    92   TRUE
4 Suresh Lucknow    60  FALSE
5  Meena    Pune    85   TRUE

Look at the data frame

  • head(participants) first 6 rows (useful for big data)

  • tail(participants) last 6 rows

  • nrow(participants) number of rows

  • ncol(participants) number of columns

  • dim(participants) rows and columns together

  • names(participants) column names

  • str(participants) structure — types of each column

  • summary(participants) quick stats for each column

Access columns using $

— gives you the whole column as a vector


participants$name
[1] "Priya"  "Rahul"  "Anita"  "Suresh" "Meena" 
participants$score
[1] 88 75 92 60 85

Access a specific [row, column]

participants[1, ] # first row, all columns
   name  city score passed
1 Priya Delhi    88   TRUE
participants[, 3] # all rows, third column (score)
[1] 88 75 92 60 85
participants[2, 3] # row 2, column 3 → Rahul's score
[1] 75

Filter rows - who passed?

participants[participants$passed == TRUE, ]
   name   city score passed
1 Priya  Delhi    88   TRUE
2 Rahul Jaipur    75   TRUE
3 Anita Mumbai    92   TRUE
5 Meena   Pune    85   TRUE

Who scored above 80?

participants[participants$score > 80, ]
   name   city score passed
1 Priya  Delhi    88   TRUE
3 Anita Mumbai    92   TRUE
5 Meena   Pune    85   TRUE

Add a new column

participants$grade <- ifelse(participants$score >= 80, "Distinction", "Pass")
participants
    name    city score passed       grade
1  Priya   Delhi    88   TRUE Distinction
2  Rahul  Jaipur    75   TRUE        Pass
3  Anita  Mumbai    92   TRUE Distinction
4 Suresh Lucknow    60  FALSE        Pass
5  Meena    Pune    85   TRUE Distinction

Your Turn

  • Create a data frame with 4 of your friends: name, age, and favourite_subject.
  • Print only the name and favourite_subject columns.
  • Filter: who is older than 25?

R Packages

R Packages 📦

“An R package is a collection of functions, data, and documentation that extends the capabilities of base R. Using packages is key to the successful use of R.”

R Packages

  • Install the R package

  • Call the R package

  • Update the R package

  • Remove the R package

Install Packages

Name of the Packages

Installed Packages

Tools \(\rightarrow\) Package Updates

Select Packages to Update

Click Install Updates

To Remove Packages

Functions for Packages


Install a Package

We install a package once

install.packages("tidyverse")

Call a Package

Call it atleast once in file

library(tidyverse)

If you un-install R or RStudio, you will lose all installed packages.

Create your own R Functions

  • A function is a reusable block of code that does one job.
  • We have already used built-in functions: mean(), sum(), c()

Basic structure of Function


my_function <- function(argument1, argument2) {
    result <- code that does something
    return(result)
}

Write a R Function


add_numbers <- function(x, y) {
  result <- x + y
  return(result)
}
  1. function name - what we call it add_numbers()
  2. An argument - what you give it function(x, y)
  3. A body - what it does with it {result <- x + y & return(result)}

Example 1 - Add two numbers

add_numbers <- function(x, y) {
  result <- x + y
  return(result)
}

add_numbers(1, 2)
[1] 3
add_numbers(3, 55)
[1] 58
add_numbers(-3, 10)
[1] 7

Example 2 - Greet a participant

greet <- function(name) {
  message <- paste("Hello,", name, "!")
  return(message)
}

greet("Kiran")
[1] "Hello, Kiran !"
greet("Ajay")
[1] "Hello, Ajay !"

Example 3 - Convert Marks to Percent

to_percent <- function(marks, total = 100) {
  # total has a default value
  percent <- (marks / total) * 100
  return(round(percent, 2)) # round to 2 decimal places
}

to_percent(75) # out of 100 (default)
[1] 75
to_percent(55, total = 60) # out of 60
[1] 91.67

Example 4 — Classify a Score

classify_score <- function(score) {
  if (score >= 90) {
    return("Excellent")
  } else if (score >= 75) {
    return("Good")
  } else if (score >= 60) {
    return("Pass")
  } else {
    return("Needs Improvement")
  }
}

classify_score(92)
[1] "Excellent"
classify_score(78)
[1] "Good"
classify_score(55)
[1] "Needs Improvement"

Your Turn

  • Write a function called celsius_to_fahrenheit that converts temperature: F = (C * 9/5) + 32.
  • Test it with 0, 100, and 37 (body temperature)

Answers

celsius_to_fahrenheit <- function(x) {
  F <- (x * 9 / 5) + 32
  return(F)
}

celsius_to_fahrenheit(37)
[1] 98.6

Quarto

Quarto

“An open-source scientific and technical publishing system”

Quarto Workflow


Create Quarto Document

Step 1

Step 2

Quarto Main Components

  1. YAML

  2. Markdown Text

  3. Code Chunk/Block/Cell

YAML

---
title: "Hello World"
subtitle: "2nd SARA Bootcamp 2026"
author: "Dr. Ajay Kumar Koli"
date: today
format: html
---

Markdown Syntax

---
title: "Hello World"
subtitle: "2nd SARA Bootcamp 2026"
author: "Dr. Ajay Kumar Koli"
date: today
format: html
---

## First Time Coding

- Relax

- Patience

## Having Fun

This is *just* the beginning. 
It will be **awesome** at the end. 
Learn more from this link <https://quarto.org/docs/reference/formats/html.html>.

## Add Image

![](images/rose.jpg)

Code Blocks

---
title: "ggplot2 demo"
author: "Norah Jones"
date: "5/22/2021"
format: 
  html:
    code-fold: true
---

## Air Quality

@fig-airquality further explores the impact of temperature on ozone level.

```{r}
#| label: fig-airquality
#| fig-cap: "Temperature and ozone level."
#| warning: false

library(ggplot2)

ggplot(airquality, aes(Temp, Ozone)) + 
  geom_point() + 
  geom_smooth(method = "loess")
```

Inline Code

---
title: "Inline Coding"
date: "3/14/2026"
format: html
---

```{r}
marks <- c(2, 4, 6, 8)
```

The sum of the marks is `{r} sum(marks)`. 

The mean of the marks is `{r} mean(marks)`. 

Quarto Output Formats

---
title: "My document"
format:
  html:
    toc: true
    html-math-method: katex
    css: styles.css
---
---
title: "My document"
format:
  pdf:
    toc: true
    number-sections: true
    colorlinks: true
---
---
title: "My Document"
format:
  docx:
    toc: true
    number-sections: true
    highlight-style: github
---

Caution

Not all YAML options are supported across every output format.

Thank you!

Module 1 complete 🎉

SARA Institute of Data Science - 3rd SARA Summer School 22-26 July 2026 “R for Researchers”