Custom Functions
Lesson 14 of 14 in Coddy's Data Manipulation in R course.
Custom functions in R are powerful tools for creating reusable code and performing complex data transformations. They allow you to encapsulate a series of operations into a single, callable unit. Let's explore how to create and use custom functions for data manipulation tasks.
Basic Structure of a Custom Function
The basic syntax for creating a custom function in R is:
function_name <- function(arg1, arg2, ...) {
# Function body
# Operations using arg1, arg2, etc.
return(result)
}Creating a Simple Custom Function
Let's create a simple function that calculates the percentage of missing values in a vector:
percent_missing <- function(x) {
sum(is.na(x)) / length(x) * 100
}
# Usage
data <- c(1, 2, NA, 4, NA, 6)
percent_missing(data) # Returns: 33.33333Functions with Multiple Arguments
Custom functions can take multiple arguments, allowing for more flexible operations:
scale_column <- function(df, column_name, min_val = 0, max_val = 1) {
df[[column_name]] <- (df[[column_name]] - min(df[[column_name]], na.rm = TRUE)) /
(max(df[[column_name]], na.rm = TRUE) - min(df[[column_name]], na.rm = TRUE))
df[[column_name]] <- df[[column_name]] * (max_val - min_val) + min_val
return(df)
}
# Usage
df <- data.frame(x = 1:10, y = 11:20)
scaled_df <- scale_column(df, "x", 0, 100)Returning Multiple Values
Functions can return multiple values using a list:
summarize_numeric <- function(x) {
list(
mean = mean(x, na.rm = TRUE),
median = median(x, na.rm = TRUE),
sd = sd(x, na.rm = TRUE)
)
}
# Usage
numbers <- c(1, 2, 3, 4, 5)
summary_stats <- summarize_numeric(numbers)Using Custom Functions with dplyr
Custom functions can be particularly useful when combined with dplyr for data manipulation:
library(dplyr)
categorize_age <- function(age) {
case_when(
age < 18 ~ "Child",
age < 65 ~ "Adult",
TRUE ~ "Senior"
)
}
# Usage with dplyr
df <- data.frame(name = c("Alice", "Bob", "Charlie"), age = c(25, 72, 16))
df %>%
mutate(age_category = categorize_age(age))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
MediumCreate a custom function named mean_score that calculates the average score for each student on a dataset of student exam scores.
To calculate the average score across each row we will use the rowwise() function and later on we will use ungroup() to return everything to where it was. Check the provided code.
Perform the following actions:
- Create a new column named
student_meanthat holds the average score. - Create a new column named
is_above_meanthat holds TRUE or FALSE if the student is above or below the average. - Create a column named
rankthat holds the place of each student relative to others based on their average. For example, 1 means the student is the best, 2 means the student is the second best, etc.- To find the rank use
order():order(order(mean_col, decreasing = TRUE))
- To find the rank use
Try it yourself
# Read input
con <- file("stdin", "r")
input_data <- readLines(con)
close(con)
# Process input data into a data frame
data <- read.csv(text = input_data, header = TRUE, stringsAsFactors = FALSE)
# Define the mean_score function
mean_score <- function(data) {
# TODO: Write your code here
# calculate the average of all subjects
return(result)
}
# TODOL Write you code here
# Create a new column named student_mean that holds the average score.
# Create a new column named is_above_mean that holds TRUE or FALSE if the student is above or below the average.
# Create a column named rank that holds the place of each student relative to others based on their average. For example, 1 means the student is the best, 2 means the student is the second best, etc.
# Print the result
print(data)