R Programming - Class 1: Data Types and Data Structures

Author

Akash Mitra

🎯 Objectives

By the end of this class, you will be able to:

  • Understand basic data types in R.
  • Identify and use common data structures in R.
  • Perform simple operations with vectors, lists, matrices, and data frames.
  • Inspect and manipulate R objects using functions like class(), typeof(), and str().

🧭 Class Outline


1. 🔰 Introduction to R and RStudio (10 min)

  • What is R and why use it?
  • Overview of RStudio:
    • Console

    • Source pane

    • Environment/History

    • Plots/Files/Packages


2. 🔡 Data Types in R (20 min)

Data Type Description Example
numeric Real numbers 3.14
integer Whole numbers 5L
character Text strings "Hello"
logical Boolean (TRUE/FALSE) TRUE
complex Complex numbers 1 + 2i

✅ Try it Out:

a <- 3.14
b <- 5L
c <- "Hello"
d <- TRUE
e <- 1 + 2i

class(a)
is.character(c)
is.logical(d)

3. 🧱 Data Structures in R (45 min)

🟦 Vectors

  • Collection of elements of the same class.
  • Created using c() which stands for concatenate.
  • Elements accessed using [], where [1] is the first element.
  • Coercion: If mixed types are provided, R coerces to a common type.
  • Vectors have only length, not dimensions.
v <- c(1, 2, 3)
names(v) <- c("One", "Two", "Three")

# check for dimension
dim(v)
NULL

🟨 Matrices

  • Matrices are vectors with a dimension attribute.
m <- matrix(1:6, nrow = 2, ncol = 3)
m
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
myrows <- c("A", "B", "C", "D")
mycol <- c("col1", "col2", "col3")

x <-  matrix(1:12, nrow = 4, ncol = 3, dimnames = list(myrows, mycol))

x
  col1 col2 col3
A    1    5    9
B    2    6   10
C    3    7   11
D    4    8   12
x[1:2, 2:3] #accessing elements in the matrix
  col2 col3
A    5    9
B    6   10

🟩 Lists

  • Lists can contain elements of different types.
  • No coercion applied.
  • Access using [ ], [[ ]], and $.
my_list <- list(name="Alice", age=25, scores=c(90, 95, 88))

# Accessing list elements
my_list[1]         # Returns a list
$name
[1] "Alice"
class(my_list[1])  # "list"
[1] "list"
my_list[[1]]       # Returns the element in its original type
[1] "Alice"
class(my_list[[1]]) # "character"
[1] "character"
my_list$name       # Returns "Alice"
[1] "Alice"

🟧 Data Frames

  • Like a table: rows and columns.
  • Columns can be of different types.
  • List of equal-length vectors
df <- data.frame(
  name = c("John", "Sara"),
  age = c(25, 30), 
  score = c(80, 95)
)

df
  name age score
1 John  25    80
2 Sara  30    95

🟥 Factors

  • Used for categorical data with levels.
g <- factor(c("male", "female", "female", "male"))
g
[1] male   female female male  
Levels: female male