Intro to dplyr
Lesson 6 of 14 in Coddy's Data Manipulation in R course.
The dplyr package is a powerful tool for data manipulation in R. It provides a set of functions that make it easy to transform and analyze data frames efficiently. In this lesson, we'll focus on three key functions: select(), filter(), and mutate().
Loading dplyr
Here is an example of how to load the package:
# Load dplyr
library(dplyr)select() Function
The select() function allows you to choose specific columns from a data frame:
# Create a sample data frame
df <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(25, 30, 35),
city = c("New York", "London", "Paris")
)
# Select specific columns
result <- select(df, name, age)
print(result)Output:
name age
1 Alice 25
2 Bob 30
3 Charlie 35filter() Function
The filter() function helps you subset rows based on specific conditions:
# Filter rows where age is greater than 28
result <- filter(df, age > 28)
print(result)Output:
name age city
1 Bob 30 London
2 Charlie 35 Parismutate() Function
The mutate() function allows you to create new columns or modify existing ones:
# Add a new column 'age_group'
result <- mutate(df, age_group = ifelse(age < 30, "Young", "Adult"))
print(result)Output:
name age city age_group
1 Alice 25 New York Young
2 Bob 30 London Adult
3 Charlie 35 Paris AdultPipe Operator %>%
dplyr introduces the pipe operator %>%, which allows you to chain multiple operations:
result <- df %>%
filter(age > 28) %>%
select(name, city) %>%
mutate(location = paste(name, "lives in", city))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.
Challenge
EasyProcess a data frame of employee information using dplyr functions. Perform the following operations:
- Select only the columns "name", "age", and "salary"
- Filter the data to include only employees who are 30 years or older
- Add a new column called "bonus" that is 10% of the salary for employees aged 40 or above, and 5% for others
- Arrange the data frame by salary in descending order
- Print the resulting data frame.
Try it yourself
# Load required library
suppressPackageStartupMessages(library(dplyr))
# Read input
con <- file("stdin", "r")
input_data <- suppressWarnings(readLines(con))
# Create data frame from input
df <- read.csv(text = input_data, stringsAsFactors = FALSE)
# TODO: Write your code below to process the data frame
process_employee_data <- function(df) {
# Your code here
# Use dplyr functions to:
# 1. Select columns
# 2. Filter data
# 3. Add bonus column
# 4. Arrange by salary
return(df) # Replace this with your processed data frame
}
# Process the data frame
result <- process_employee_data(df)
# Print the result
print(result)