Menu
Coddy logo textTech

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  Paris
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

You are provided with a data frame containing information about students. Your task is to perform the following operations:

  1. Subset the data frame to include only students who are older than 20 years.
  2. From this subset, select only the "name" and "score" columns.
  3. Calculate and print the average score of these students.
  4. 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