Programming Using R Studio
By: Asfand Gul Kasi
Programming with R and RStudio: Essential Tools for Data Analysis
Programming Fundamentals
R acts as the engine behind data analysis, while RStudio serves as the control interface, helping users navigate programming tasks efficiently. Understanding the basics of programming in R is essential, as it differs from traditional platforms like spreadsheets and SQL, offering more flexibility and power for data manipulation.
Coding in RStudio
The course introduces core programming concepts, including syntax for calculations, naming conventions and the use of pipes to streamline workflows. Learners will also explore R packages, especially the Tidyverse, a collection of community-developed tools designed for a variety of data tasks.
Working with Data
Students will learn to install and leverage the Tidyverse packages, including ggplot2 for powerful data visualization. Emphasis is placed on hands-on practice through RStudio Cloud, preparing learners to tackle real-world data analysis projects confidently.
Programming Fundamentals in R
To get started with R, it’s important to understand six fundamental concepts: functions, comments, variables, data types, vectors, and pipes.
- Functions are reusable code blocks that perform specific tasks. For example,
print("Coding in R")displays text in RStudio. Functions may take arguments, values passed inside parentheses. Functions are case-sensitive. - Comments start with
#and are used to explain code, making scripts more readable. - Variables store values for later use. For example,
first_variable <- "This is my variable"
second_variable <- 12.5first_variable <- "This is my variable" second_variable <- 12.5- Variable names must start with letters and are case-sensitive.
- Data types include text, numeric, logical, date, and date-time. Each variable has a type that determines how it can be used.
- Vectors are sequences of elements of the same type, created with
c(). Example:
vec_1 <- c(1, 2, 3, 4)vec_1 <- c(1, 2, 3, 4)- Pipes (
%>%) pass the output of one function to another, making code more readable and efficient, especially for chaining multiple operations.
Together, these “super six” fundamentals form the foundation for programming in R and performing data analysis. Learning to use them effectively will make coding in R easier, cleaner, and more powerful.
Vectors and Lists in R
In R, data structures organize and store data. Common types include vectors, data frames, matrices, and arrays. This guide focuses on vectors and lists.
Vectors
Vectors are one-dimensional sequences of elements of the same type.
Types of Atomic Vectors
- Logical — TRUE/FALSE
- Integer — Whole numbers (e.g.,
3L) - Double — Decimal numbers (e.g.,
101.175) - Character — Strings (e.g.,
"Coding")
Integers and doubles together are called numeric vectors.
Creating Vectors
c()function: combines values into a vector
c(2.5, 48.5, 101.5) # numeric
c(1L, 5L, 15L) # integer
c("Sara", "Lisa", "Anna") # character
c(TRUE, FALSE, TRUE) # logical- Sequences:
z <- c(4:10)
Vector Properties
- Type:
typeof()oris.integer()/is.character()/is.logical()/is.double() - Length:
length()
x <- c(33.5, 57.75, 120.05)
length(x) # 3Naming Vectors
x <- c(1, 3, 5)
names(x) <- c("a", "b", "c")
x["b"] # access by name
x[2] # access by indexLists
Lists are more flexible than vectors because elements can be of any type: characters, numbers, logicals, vectors, matrices, data frames, or even other lists.
Creating Lists
list("a", 1L, 1.5, TRUE) # different types
list(list(list(1, 3, 5))) # nested listsInspecting List Structure
Use str() to explore a list:
str(list("a", 1L, 1.5, TRUE))
z <- list(list(list(1, 3, 5)))
str(z)$symbols instr()indicate nested levels.
Naming List Elements
list('Chicago' = 1, 'New York' = 2, 'Los Angeles' = 3)Dates and Times in R
In R, dates and times are handled using base R and the lubridate package from the tidyverse.
Setup
Install tidyverse (if not already installed):
install.packages("tidyverse")Load tidyverse and lubridate:
library(tidyverse)
library(lubridate)Date and Time Types
R recognizes three types of temporal data:
- Date — calendar day:
"2016-08-16" - Time — time of day:
"20:11:59 UTC" - Date-time — combination:
"2018-03-31 18:15:48 UTC"
- Current date:
today()→"yyyy-mm-dd" - Current date-time:
now()→"yyyy-mm-dd hh:mm:ss UTC"
UTC = Universal Coordinated Time
Creating Dates from Strings
Use lubridate functions to parse strings into dates. Functions are based on the order of year (y), month (m), day (d):
ymd("2023-01-20") # yyyy-mm-dd
mdy("January 20th, 2023") # mm-dd-yyyy
dmy("20-Jan-2021") # dd-mm-yyyy- Can also use numeric input:
ymd(20210120) → "2021-01-20"
Creating Date-Times from Strings
Add _h, _hm, or _hms to include hours, minutes, and seconds:
ymd_hms("2021-01-20 20:11:59") # includes hours, minutes, seconds
mdy_hm("01/20/2021 08:01") # includes hours and minutesConverting Date-Time to Date
Use as_date() to extract only the date from a date-time:
as_date(now()) # returns current date without timeResources for more information
Dates and times with lubridate: Cheat Sheet: This resource provides a detailed map of all the different things you can do with the lubridate package.
lubridate.tidyverse: This is the “lubridate” entry from the official tidyverse documentation, which offers a comprehensive reference guide to the various tidyverse packages.
Other Common Data Structures in R
R offers several ways to organize data beyond vectors and lists, including data frames, matrices, and files.
Data Frames
A data frame is like a spreadsheet or SQL table:
- Structure: Columns = variables, Rows = observations
- Column rules:
- Each column has a name
- Each column contains one type of data (numeric, logical, or character)
- Each cell holds a single element
Creating Data Frames
Use data.frame() with vectors as columns:
z <- data.frame(x = c(1, 2, 3), y = c(1.5, 5.5, 7.5))Accessing Elements
Use the extract operator [row, column]:
z[2, 1] # returns 2 (second row, first column)Files (Optional)
R can create, copy, and delete files:
- Create:
file.create("file_name.csv")→ TRUE if successful - Copy:
file.copy("file.txt", "destination_folder") - Delete:
unlink("file_name.csv")
Files are often used to import or export data in analysis workflows.
Matrices (Optional)
A matrix is a two-dimensional collection of data with only one data type.
Creating Matrices
Use the matrix() function:
matrix(c(3:8), nrow = 2) # 2 rows, 3 columns
matrix(c(3:8), ncol = 2) # 3 rows, 2 columns (R infers rows automatically)Accessing Elements
Like data frames, use [row, column] to extract specific elements.
Using Operators in R for E-Commerce Data Analysis
Understanding Operators in R
Operators in R are symbols that tell the program what type of calculation or action to perform. They are essential in data analysis because they allow analysts to manipulate, compare, and calculate values efficiently. In e-commerce analysis, operators help calculate totals, discounts, profits, and performance metrics.
Get Asfand Gul Kasi’s stories in your inbox
Join Medium for free to get updates from this writer.
Assignment operators, such as <-, are used to store values in variables or vectors, making data easy to reuse later in scripts and calculations.
Arithmetic Operators
Arithmetic operators perform basic mathematical operations commonly needed in sales analysis:
- Plus (
+) – adds values (e.g., total sales) - Minus (
-) – subtracts values (e.g., refunds from revenue) - Asterisk (
*) – multiplies values (e.g., price × quantity) - Slash (
/) – divides values (e.g., average order value)
Practical Application in R
In practice, analysts assign sales figures to variables and apply arithmetic operators to analyze revenue, costs, and profits. For example, daily sales, discounts, and taxes can be calculated quickly using simple formulas.
Saving scripts in RStudio is emphasized, as it helps maintain a clear record of analysis, ensures reproducibility, and allows future updates as new sales data becomes available.
Logical Operators and Conditional Statements
1. Logical Operators in R
Logical operators are used to compare values and return TRUE or FALSE. They are very useful for filtering datasets.
AND (&)
Returns TRUE only if both conditions are TRUE.
airquality$Solar.R > 150 & airquality$Wind > 10TRUE when it is both very sunny and very windy
OR (|)
Returns TRUE if at least one condition is TRUE.
airquality$Solar.R > 150 | airquality$Wind > 10TRUE when it is sunny OR windy (or both)
NOT (!)
Reverses a logical condition.
airquality$Day != 1TRUE for all days except the 1st
Combined example:
!(airquality$Solar.R > 150 | airquality$Wind > 10)TRUE when it is neither very sunny nor very windy
2. Using Logical Operators with Data
Logical expressions return a logical vector, which can be used to:
- Filter rows
- Create subsets
- Apply conditions
Example:
airquality[airquality$Temp > 85, ]Returns only hot days
3. Conditional Statements in R
Conditional statements allow R to make decisions.
if()
Runs code only when a condition is TRUE.
x <- 4
if (x > 0) {
print("x is a positive number")
}if() ... else
Runs one block if TRUE another if FALSE.
x <- -7
if (x > 0) {
print("x is positive")
} else {
print("x is zero or negative")
}if() ... else if() ... else
Used for multiple conditions (checked in order).
x <- 0
if (x < 0) {
print("Negative")
} else if (x == 0) {
print("Zero")
} else {
print("Positive")
}R stops checking as soon as one condition is TRUE
4. Real Example with airquality
ozone_level <- airquality$Ozone[1]if (is.na(ozone_level)) {
print("Ozone reading is missing")
} else if (ozone_level < 30) {
print("Low ozone level")
} else if (ozone_level < 100) {
print("Moderate ozone level")
} else {
print("High ozone level")
}Handles missing values and multiple categories
Concept of R Packages
Understanding R Packages
R packages are collections of reusable R code developed by the R community to make programming and data analysis easier and more efficient. Each package typically includes functions, documentation, sample datasets, and tests to ensure the code works correctly. Packages help analysts avoid writing repetitive code and promote reproducibility.
Using R Packages in RStudio
R comes with several base packages that are available automatically when you start RStudio. Some recommended packages must be loaded using the library() function before use. To see which packages are installed on your system, you can use the installed.packages() command.
Exploring Additional Packages
In addition to pre-installed packages, thousands of packages are available online. CRAN (Comprehensive R Archive Network) is the main repository for R packages. These packages expand R’s capabilities, enabling advanced data analysis, visualization, and modeling tasks efficiently.
Available R Packages
To fully use R for data analysis, you need to install packages. R packages are collections of reusable code created and shared by the R community. They add new features and tools to R, making data analysis faster and more powerful.
Where to Find R Packages
Packages are stored in repositories, which are online collections of ready-to-install packages. Common repositories include:
- CRAN (Comprehensive R Archive Network)
- Bioconductor
- R-Forge
- rOpenSci
- GitHub
Package Documentation
Each package comes with documentation that explains:
- The package author
- What the package does
- Required dependencies
On CRAN this information is found in the DESCRIPTION file.
Choosing the Right Packages
With thousands of packages available, helpful resources include:
- Tidyverse: A popular collection of packages designed for data manipulation, visualization and analysis
- RStudio’s Quick List of Useful Packages: Includes installation guides and use cases
- CRAN Task Views: Organizes packages by task (e.g., data mining, visualization & machine learning)
Importance of R Packages and the Tidyverse in Data Analysis
R Packages and the Tidyverse
R packages enhance the data analysis process by providing reusable functions, documentation and sample datasets created by the R community. They save time, improve accuracy and support reproducible analysis.
The tidyverse is a collection of R packages specifically designed for data manipulation, exploration, and visualization. It is essential for data analysts because it promotes consistent syntax and efficient workflows. Core tidyverse packages include ggplot2, dplyr, tidyr and readr.
Installation and Usage
The tidyverse can be installed from CRAN using:
install.packages("tidyverse")After installation, it is loaded with:
library(tidyverse)Loading tidyverse automatically loads several commonly used packages such as ggplot2 and dplyr.
Package Management
Keeping packages updated ensures access to new features and bug fixes. Packages can be updated using:
tidyverse_update()or
install.packages("package_name")Users should also watch for conflict messages, which occur when different packages contain functions with the same name. In such cases, R uses the function from the package loaded most recently.
Next Steps
As you continue learning R, you will explore the tidyverse in greater depth and understand how it plays a central role in modern efficient data analysis workflows.
Core Features of the Tidyverse
Core Packages of the Tidyverse
The tidyverse is a collection of R packages designed to make data analysis efficient, readable and consistent.
- ggplot2: Used for data visualization, enabling analysts to create a wide range of plots by mapping data variables to visual elements.
- tidyr: Helps clean and organize data so it is tidy, meaning each variable, observation and value is stored in the correct place.
Data Import and Manipulation
- readr: Makes importing data into R fast and simple especially CSV files using functions like
read_csv(). - dplyr: Provides clear and consistent functions for data manipulation tasks such as selecting columns, filtering rows and transforming variables.
Additional Tidyverse Packages
- tibble: A modern version of data frames with improved printing and usability.
- purrr: Supports functional programming by working efficiently with functions and vectors.
- stringr: Simplifies working with text and strings.
- forcats: Helps manage and reorder factors, which represent categorical data.
Use of Pipes in R Programming
A pipe is a tool in R that passes the output of one function directly into the next function as its input. This creates a clear sequence of operations and avoids deeply nested functions, making code easier to read and understand.
Using Pipes in R
Pipes are written using the operator %>%, commonly used in the tidyverse. For example, when working with datasets like ToothGrowth, pipes allow analysts to filter, transform and sort data step by step in a logical order.
Benefits of Using Pipes
Using pipes improves code readability, reduces errors and makes analysis easier to modify or extend. Pipes act as building blocks for data cleaning, transformation and analysis helping analysts write efficient and maintainable R code.
The End
Thank You For Reading









