HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • R Code Examples
    • R Code to Create and Manipulate Vectors
    • R Code to Work with Data Frames
    • R Code to Handle Factors and Categorical Data
    • Example R Code for Basic Data Visualization with ggplot2
    • R Code to Aggregate Data Using dplyr
    • R Code to Apply Functions with lapply and sapply
    • R Code to Handle Missing Data
    • Example R Code for String Manipulation with stringr
    • R Code to Transform Data with tidyr
    • R Code to Perform ADF Test
    • R Code to Perform Data Import and Export with CSV
    • R Code for Filtering Data
    • R Code for Easily Summarizing Data
    • R Code to Perform Linear Regression for Statistical Analysis
    • R Code to Perform t-tests for Statistical Analysis
    • Example R Code for Time Series Analysis
    • R Code for Doing Web Scraping with Examples
    • R Code to Showcase Geospatial Analysis
    • Example R Code to Filter Multiple Conditions (for Data Manipulation)

R Code to Apply Functions with lapply and sapply

Introduction to lapply and sapply

In R, `lapply()` and `sapply()` are essential functions for applying operations over lists and vectors. They provide a way to perform repetitive tasks efficiently. Both functions streamline data manipulation by reducing the need for explicit loops.

The `lapply()` function returns a list, preserving the input data’s structure. It applies a function to each element of a list and returns a list of the same length. This is useful for operations where maintaining the data’s structure is important.

On the other hand, `sapply()` simplifies the result, often returning a vector or matrix. It is ideal when you want a more compact output. Both functions enhance data processing by allowing functional programming techniques in R.

Using lapply

The lapply() function applies a function to each element of a list and returns a list. It is useful for operations where you need to keep the structure of the data.

# Sample list
data_list <- list(
  numbers = 1:5,
  letters = letters[1:5]
)

# Apply function using lapply
result_lapply <- lapply(data_list, function(x) {
  if (is.numeric(x)) {
    sum(x)
  } else {
    paste(x, collapse = "")
  }
})
result_lapply

Output:

$numbers
[1] 15

$letters
[1] "abcde"

In this example, lapply() calculates the sum of numeric vectors and concatenates character vectors. The result is a list with the sum and concatenated string.

Using sapply

The sapply() function is similar to lapply(), but it simplifies the result. It returns a vector or matrix when possible, making it more compact and easier to work with.

# Apply function using sapply
result_sapply <- sapply(data_list, function(x) {
  if (is.numeric(x)) {
    sum(x)
  } else {
    paste(x, collapse = "")
  }
})
result_sapply

Output:

 numbers letters 
     15     "abcde"

Here, sapply() produces a named vector where numeric results are summed and character vectors are concatenated. This output is simpler and more compact compared to the list returned by lapply().

Comparison of lapply and sapply

Comparison Table
Featurelapplysapply
Return TypeAlways returns a listAttempts to simplify the result to a vector or matrix
Output StructurePreserves the structure of the input dataSimplifies output to a more compact form when possible
UsageUseful when the structure of the result needs to be a listIdeal when a vector or matrix output is desired
PerformanceMay be slower due to list overheadGenerally faster if simplification is possible
Handling Non-Uniform ResultsHandles non-uniform results by returning a listMay not handle non-uniform results well; could return unexpected structures
Typical OutputA list with the same length as the inputA vector or matrix, depending on the result’s simplicity
Related Articles
  • R Code to Transform Data with tidyr
  • Example R Code for String Manipulation with stringr
  • R Code to Handle Missing Data
  • R Code to Aggregate Data Using dplyr
  • Example R Code for Basic Data Visualization with ggplot2
  • R Code to Handle Factors and Categorical Data

No luck finding what you need? Contact Us

Previously
R Code to Aggregate Data Using dplyr
Up Next
R Code to Handle Missing Data
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.