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 Transform Data with tidyr

`tidyr` is a package in R designed for tidying and transforming data. It helps convert data into a format that is easier to analyze. The package is built on the principle that tidy data is essential for efficient data manipulation.

With `tidyr`, you can reshape data, convert between wide and long formats, and separate or unite columns.

It simplifies tasks such as spreading key-value pairs across columns or gathering multiple columns into a single key-value pair. These transformations make data preparation more straightforward.

Using `tidyr` effectively can streamline your data analysis workflow. By learning functions like `pivot_longer()`, `pivot_wider()`, and `separate()`, you can manage your datasets more efficiently.

This preparation is crucial for performing accurate and meaningful analyses.

Example Code

library(tidyr)
library(dplyr)

# Sample data
data <- tibble(
  id = 1:3,
  name = c("John", "Jane", "Doe"),
  math = c(90, 80, 70),
  english = c(85, 90, 75)
)

# 1. Pivot longer
data_long <- data %>%
  pivot_longer(cols = c(math, english), names_to = "subject", values_to = "score")
print(data_long)
# Output: 
# # A tibble: 6 × 3
#      id name  subject  score
#        
# 1     1 John  math      90
# 2     1 John  english   85
# 3     2 Jane  math      80
# 4     2 Jane  english   90
# 5     3 Doe   math      70
# 6     3 Doe   english   75

# 2. Pivot wider
data_wide <- data_long %>%
  pivot_wider(names_from = subject, values_from = score)
print(data_wide)
# Output: 
# # A tibble: 3 × 4
#      id name  math english
#        
# 1     1 John    90      85
# 2     2 Jane    80      90
# 3     3 Doe     70      75

# 3. Separate columns
data_separated <- data_long %>%
  separate(name, into = c("first_name", "last_name"), sep = " ")
print(data_separated)
# Output: 
# # A tibble: 6 × 4
#      id first_name last_name subject  score
#                 
# 1     1 John      NA        math      90
# 2     1 John      NA        english   85
# 3     2 Jane      NA        math      80
# 4     2 Jane      NA        english   90
# 5     3 Doe       NA        math      70
# 6     3 Doe       NA        english   75

Detailed Explanation

  • Pivot Longer: The pivot_longer() function transforms data from a wide format to a long format. In the example, it takes the math and english columns and combines them into a single subject column, with corresponding score values.
  • Pivot Wider: The pivot_wider() function converts data from a long format back to a wide format. Here, it separates the subject column into individual columns, such as math and english, with their respective score values.
  • Separate Columns: The separate() function splits a single column into multiple columns based on a delimiter. In this case, it splits the name column into first_name and last_name columns.

Conclusion

Using `tidyr` effectively can greatly enhance your data manipulation skills in R.

Here are the 5 key points for beginners:

  • Wide to Long: Use pivot_longer() to convert wide data into a long format.
  • Long to Wide: Use pivot_wider() to convert long data back into a wide format.
  • Separate Columns: Use separate() to split a single column into multiple columns.
  • Combine Columns: Use unite() to merge multiple columns into one.
  • Data Cleaning: Use these tools to tidy data, making it ready for analysis.
Related Articles
  • Example R Code for String Manipulation with stringr
  • R Code to Handle Missing Data
  • R Code to Apply Functions with lapply and sapply
  • 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
Example R Code for String Manipulation with stringr
Up Next
R Code to Perform ADF Test
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.