Dataframe Indexing
Lesson 2 of 14 in Coddy's Data Manipulation in R course.
Understanding how to index and subset data frames is crucial for effective data manipulation. Let's explore various methods of indexing in data frames.
Here is a dataframe we will work with as example:
df <- data.frame(
name = c("Alice", "Bob", "Charlie", "David", "Eve"),
age = c(25, 30, 35, 28, 22),
city = c("New York", "London", "Paris", "Tokyo", "Sydney"),
salary = c(50000, 60000, 75000, 55000, 45000)
)Indexing By Position
# Single element df[2, 3] # Returns the element in the 2nd row and 3rd column (character: "London")# Entire row df[3, ] # Returns the 3rd row as a data frame with 1 row and all columns# Entire column df[, 2] # Returns the 2nd column as a vector df[[2]] # Also returns the 2nd column as a vector# Multiple rows or columns: df[1:3, ] # Returns the first 3 rows df[, c(1, 3)] # Returns the 1st and 3rd columns
Indexing by Name
# Single column df$age # Returns the "age" column as a vector df[["age"]] # Also returns the "age" column as a vector# Multiple columns df[c("name", "city")] # Returns a data frame with "name" and "city" columns
Logical Indexing
df[df$age > 30, ] # Returns rows where age is greater than 30
Combining Methods
df[df$salary > 50000, "name"] # Returns names of people with salary > 50000
Adding and Modifying Data
# Adding a new column df$department <- c("HR", "IT", "Finance", "Marketing", "Sales")# Modifying existing data df[df$name == "Alice", "salary"] <- 52000
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Try it yourself
This lesson doesn't include a code challenge.
All lessons in Data Manipulation in R
1Data Basics
Understanding Data StructuresDataframe IndexingSubsetting DataData Type ConversionThe Pipe Operator in R