Learning001

1. R and RStudio Fundamentals

This session establishes the foundation for everything we will do in R. The objective is to understand what R is, what RStudio does, how the interface works, where to write code, how to execute commands and how to organise an R project properly.

1.1. What is R?

R is a programming language and statistical computing environment.

It is commonly used for:

  • Data analysis

  • Statistical analysis

  • Data cleaning

  • Data visualization

  • Machine learning

  • Forecasting

  • Research

  • Reporting

  • Reproducible analytical work

R contains built-in functions for statistics and data manipulation. Additional functionality is added through packages.

For Example:

sales <- c(25000, 30000, 45000, 52000)

mean(sales)
[1] 38000

In the above code, R stores four sales values and calculates their average.

In R, c() means “combine” or “concatenate.” It combines several values into a single vector.

In the above code:

  • sales is the variable name.

  • <- assigns a value to the variable.

  • c() combines the four sales figures.

  • The result is a numeric vector stored in sales.

1.2. What is RStudio?

RStudio is an Integrated Development Environment, commonly called an IDE.

It provides a user-friendly interface for writing and executing R code. It includes a code editor, Console, Environment pane, plotting tools, package management, debugging facilities and document-authoring features.

RStudio does not replace R.

The relationship is:

R       = programming language and analytical engine 

RStudio = application used to work conveniently with R

A useful comparison is:

Python + Jupyter Notebook 

R + RStudio

You normally install R first and RStudio afterward.

2. Working with Variable in R

2.1. Working with Variables in R

A variable is a named storage location used to hold data in R. Variables are commonly created with the assignment operator <-, although = can also be used. For example, sales <- 50000 stores the value 50000 in a variable called sales. Variable names should be meaningful, must not begin with a number, and should not contain spaces. R variables can store numbers, text, logical values, vectors, data frames, and other types of data.

2.2. Object Naming Rules

Valid object names include:

sales

monthly_sales

sales2026

totalRevenue

student_count

Avoid names like:

monthly sales

2026sales 

total-revenue

Recommended style:

monthly_sales 

total_revenue 

employee_count

This is called snake_case.

R is case-sensitive:

sales 

Sales 

SALES

These are three different names.

3. Using Comments

Comments explain your code:

# Store monthly revenue
monthly_revenue <- 450000

# Store monthly expenses
monthly_expenses <- 280000

# Calculate profit
monthly_profit <- monthly_revenue - monthly_expenses

monthly_profit
[1] 170000

Good comments explain the purpose of the code, not merely repeat the code.

Less useful:

# Subtract expenses from revenue
monthly_profit <- monthly_revenue - monthly_expenses

More useful:

# Calculate operating profit before tax
monthly_profit <- monthly_revenue - monthly_expenses

4. Working with Data Type in R

Data Types in R

Data types describe the kind of value stored in a variable. The main data types in R are numeric, integer, character, logical, complex, and raw. R automatically identifies the data type of a value, but you can check it using class() or typeof().

# Numeric 

price <- 2500.50 
class(price) 
[1] "numeric"
# Integer 

quantity <- 10L 
class(quantity) 
[1] "integer"
# Character 

product <- "Laptop" 
class(product) 
[1] "character"
# Logical 

in_stock <- TRUE 
class(in_stock) 
[1] "logical"
# Complex 

number <- 4 + 3i 
class(number)
[1] "complex"

You can also convert values from one data type to another:

amount_text <- "5000"  

amount_number <- as.numeric(amount_text) 

amount_character <- as.character(amount_number) 

amount_integer <- as.integer(amount_number) 

amount_logical <- as.logical(1)

Common conversion functions include as.numeric(), as.character(), as.integer(), and as.logical().

5. Statistical Functions in R

R provides several built-in statistical functions for analysing numerical data. The mean() function calculates the average, median() returns the middle value, sum() calculates the total, while min() and max() return the lowest and highest values. The sd() function measures standard deviation, and var() calculates variance. Other useful functions include range() for the minimum and maximum values, quantile() for quartiles and percentiles, length() for counting observations, and summary() for generating a quick statistical summary of the data. When a dataset contains missing values, use na.rm = TRUE to exclude them from the calculation.

sales_val <- c(3000, 8900, 4500, 7000, 8000, 2300, 3400, 7000)
mean(sales_val)
[1] 5512.5
sum(sales_val)
[1] 44100
max(sales_val)
[1] 8900
min(sales_val)
[1] 2300
length(sales_val)
[1] 8
sd(sales_val)
[1] 2513.073
summary(sales_val)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   2300    3300    5750    5512    7250    8900 
range(sales_val)
[1] 2300 8900
quantile(sales_val)
  0%  25%  50%  75% 100% 
2300 3300 5750 7250 8900 
# difference between the Max and Min (range)

diff(range(sales_val))
[1] 6600
# Quartiles and Percentiles

quantile(sales_val, 0.25)   # 25th percentile
 25% 
3300 
quantile(sales_val, 0.50)   # 50th percentile or median
 50% 
5750 
quantile(sales_val, 0.75)   # 75th percentile
 75% 
7250 
quantile(sales_val, 0.90)   # 90th percentile
 90% 
8270 
table(sales_val)
sales_val
2300 3000 3400 4500 7000 8000 8900 
   1    1    1    1    2    1    1 
# Count unique values

length(unique(sales_val))
[1] 7
# Display the unique values

unique(sales_val)
[1] 3000 8900 4500 7000 8000 2300 3400
# Finding Positions

# Position of the Minimum value:

which.min(sales_val)
[1] 6
# Position of the Maximum value:

which.max(sales_val)
[1] 2
# Find values above 30000

sales_val
[1] 3000 8900 4500 7000 8000 2300 3400 7000
which(sales_val > 3000)
[1] 2 3 4 5 7 8
# Cummulative statistics

cumsum(sales_val)       # Running total
[1]  3000 11900 16400 23400 31400 33700 37100 44100
cummax(sales_val)       # Running maximum
[1] 3000 8900 8900 8900 8900 8900 8900 8900
cummin(sales_val)       # Running minimum
[1] 3000 3000 3000 3000 3000 2300 2300 2300
cumprod(sales_val)      # Running product
[1] 3.000000e+03 2.670000e+07 1.201500e+11 8.410500e+14 6.728400e+18
[6] 1.547532e+22 5.261609e+25 3.683126e+29
# Finding Correlation and Covariance for Two Numerical Variables

sales <- c(25000, 30000, 45000, 52000, 30000)
quantity <- c(5, 7, 10, 12, 6)

cor(sales, quantity)    # Correlation
[1] 0.9915218
cov(sales, quantity)    # Covariance
[1] 33250
# Sorting and Ranking

sort(sales_val)                     # Ascending order
[1] 2300 3000 3400 4500 7000 7000 8000 8900
sort(sales_val, decreasing = TRUE)  # Descending order
[1] 8900 8000 7000 7000 4500 3400 3000 2300
rank(sales_val)                     # Rank each value
[1] 2.0 8.0 4.0 5.5 7.0 1.0 3.0 5.5
# Missing Values Functions

is.na(sales_val)            # Check for missing values
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
anyNA(sales_val)            # Check whether any NA exists
[1] FALSE
sum(is.na(sales_val))       # Count missing values
[1] 0
na.omit(sales_val)          # Remove missing values
[1] 3000 8900 4500 7000 8000 2300 3400 7000

Mode in R

Base R does not have a direct statistical mode function. mode() in R describes an object’s storage type, not the most frequent value.

You can find the statistical mode with:

names(sort(table(sales_val), decreasing = TRUE))[1]
[1] "7000"

Useful complete analysis

sales_val <- c(25000, 30000, 45000, 52000, 30000)

mean(sales_val)
[1] 36400
median(sales_val)
[1] 30000
sum(sales_val)
[1] 182000
min(sales_val)
[1] 25000
max(sales_val)
[1] 52000
range(sales_val)
[1] 25000 52000
sd(sales_val)
[1] 11502.17
var(sales_val)
[1] 132300000
quantile(sales_val)
   0%   25%   50%   75%  100% 
25000 30000 30000 45000 52000 
length(sales_val)
[1] 5
table(sales_val)
sales_val
25000 30000 45000 52000 
    1     2     1     1 
summary(sales_val)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  25000   30000   30000   36400   45000   52000