Subsetting Data
Lesson 3 of 14 in Coddy's Data Manipulation in R course.
Subsetting data is a crucial skill in R that allows you to extract specific portions of your data.
The subset() function provides a convenient way to subset data frames.
df <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(25, 30, 35),
city = c("New York", "London", "Paris")
)# Subsetting rows
result <- subset(df, age > 28)
print(result)Output:
name age city
2 Bob 30 London
3 Charlie 35 Paris# Subsetting columns
result <- subset(df, select = c("name", "city"))
print(result)Output:
name city
1 Alice New York
2 Bob London
3 Charlie ParisThis 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
EasyYou are provided with a data frame containing information about students. Your task is to perform the following operations:
- Subset the data frame to include only students who are older than 20 years.
- From this subset, select only the "name" and "score" columns.
- Calculate and print the average score of these students.
- Identify and print the name of the student with the highest score.
Try it yourself
# Read input
con <- file("stdin", "r")
input_data <- suppressWarnings(readLines(con))
# Create data frame from input
df <- read.csv(text = input_data, header = TRUE, stringsAsFactors = FALSE)
# TODO: Write your code below
# 1. Subset the data frame for students older than 20
# 2. Select only the "name" and "score" columns
# 3. Calculate the average score
# 4. Find the student with the highest score
# Print results (update these with your calculations)
cat("Average score:", 0, "\n")
cat("Student with highest score:", "", "\n")All lessons in Data Manipulation in R
1Data Basics
Understanding Data StructuresDataframe IndexingSubsetting DataData Type ConversionThe Pipe Operator in R