R Tutorial



R DATA STRUCTURES


Data Structures in R

Data structures organize and store data in R for easy access and manipulation. Understanding data structures is essential for effective programming and data analysis in R.

1. Vectors

The simplest data structure in R. A vector is a sequence of elements of the same type (numeric, character, logical, etc.).

# Numeric vector
num_vec <- c(1, 2, 3, 4, 5)

# Character vector
char_vec <- c("apple", "banana", "cherry")

# Logical vector
log_vec <- c(TRUE, FALSE, TRUE)
  

2. Lists

Lists are collections of elements that can be of different types (numbers, strings, vectors, even other lists).

my_list <- list(
  name = "Alice",
  age = 25,
  scores = c(85, 90, 88),
  married = FALSE
)
  

You can access list elements by name or position:

my_list$name       # "Alice"
my_list[[3]]       # c(85, 90, 88)
  

3. Matrices

Matrices are 2-dimensional arrays with elements of the same type, arranged in rows and columns.

mat <- matrix(1:6, nrow=2, ncol=3)
print(mat)

# Output:
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6
  

4. Arrays

Arrays can have more than two dimensions. They store data of the same type.

arr <- array(1:12, dim = c(2, 3, 2))
print(arr)
  

5. Data Frames

Data frames are 2-dimensional tabular data structures like spreadsheets or SQL tables. Columns can be different types.

df <- data.frame(
  id = 1:3,
  name = c("John", "Jane", "Tom"),
  age = c(28, 25, 31),
  married = c(TRUE, FALSE, TRUE)
)
print(df)
  

6. Factors

Factors represent categorical data with fixed possible values called levels.

colors <- factor(c("red", "blue", "red", "green"))
print(colors)
levels(colors)   # Shows possible categories: "blue", "green", "red"
  

Summary

  • Vectors: Homogeneous, 1D sequences.
  • Lists: Heterogeneous, can contain mixed types.
  • Matrices: 2D, homogeneous.
  • Arrays: Multi-dimensional, homogeneous.
  • Data Frames: 2D, heterogeneous, tabular.
  • Factors: Categorical data with fixed levels.

Practice Exercises

  • Create a numeric vector and find its mean.
  • Make a list with your name, age, and a vector of your favorite numbers.
  • Create a 3x3 matrix and access its element in row 2, column 3.
  • Build a data frame for 3 students with columns: Name, Score, Passed (TRUE/FALSE).
  • Convert a character vector to a factor and print its levels.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review