Menu
Coddy logo textTech

Understanding Data Structures

Lesson 1 of 14 in Coddy's Data Manipulation in R course.

In R, data structures are fundamental for organizing and manipulating data. Let's explore three basic data structures: vectors, matrices, and data frames.

1. Vectors

Vectors are one-dimensional arrays that can hold elements of the same data type.


# Creating a numeric vector
numbers <- c(1, 2, 3, 4, 5)

# Creating a character vector
fruits <- c("apple", "banana", "cherry")

# Accessing elements
print(numbers[2])  # Output: 2
print(fruits[1:2])  # Output: "apple" "banana"

2. Matrices

Matrices are two-dimensional arrays with rows and columns, containing elements of the same data type.


# Creating a matrix
mat <- matrix(1:6, nrow = 2, ncol = 3)

# Accessing elements
print(mat[1, 2])  # Returns the element in the 1st row and 2nd column (Output: 3)
print(mat[, 1])   # Returns the 1st column as a vector (Output: 1 2)

3. Data Frames

Data frames are table-like structures that can hold different data types in each column.


# Creating a data frame
df <- data.frame(
  name = c("Alice", "Bob", "Charlie"),
  age = c(25, 30, 35),
  city = c("New York", "London", "Paris")
)

# Accessing elements
print(df$name)        # Returns the column named "name" (Output: "Alice" "Bob" "Charlie")
print(df[2, "age"])   # Output: 30
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Perform the following operations to the dataframe:

  1. Add a new column called "height_m" that converts the height from centimeters to meters
  2. Calculate and print the average age
  3. Print the name of the tallest person (in meters)

Try it yourself

# Read input
con <- file("stdin", "r")
input_data <- suppressWarnings(readLines(con, n = 3))

# Process input data
data_list <- strsplit(input_data, ",")
names <- sapply(data_list, function(x) x[1])
ages <- as.numeric(sapply(data_list, function(x) x[2]))
heights <- as.numeric(sapply(data_list, function(x) x[3]))

# Create the initial data frame
df <- data.frame(
  name = names,
  age = ages,
  height = heights
)

# TODO: Write your code below
# 1. Add a new column 'height_m'
# 2. Calculate and print the average age
# 3. Print the name of the tallest person (in meters)

# Placeholder for output
cat("Average age:", avg_age, "\n")
cat("Tallest person:", tallest_person)

All lessons in Data Manipulation in R