0
0
R Programmingprogramming~30 mins

pivot_wider (long to wide) in R Programming - Mini Project: Build & Apply

Choose your learning style9 modes available
Pivoting Data from Long to Wide Format with pivot_wider
📖 Scenario: Imagine you have survey data collected from different people about their favorite fruits. The data is in a long format, where each row shows one person's choice for one fruit type. You want to reshape this data so that each person has one row, and their favorite fruits are shown in separate columns.
🎯 Goal: You will learn how to use the pivot_wider function from the tidyr package in R to convert data from long format to wide format. This will help you organize data better for analysis or reporting.
📋 What You'll Learn
Create a data frame called survey_data with specific columns and values.
Create a variable called fruit_column to specify the column to spread.
Use pivot_wider to reshape the data from long to wide format.
Print the resulting wide data frame.
💡 Why This Matters
🌍 Real World
Pivoting data from long to wide format is common in data analysis when you want to compare categories side by side, like survey responses or sales data.
💼 Career
Data analysts and scientists often reshape data to prepare it for visualization, modeling, or reporting. Knowing pivot_wider helps you organize data efficiently.
Progress0 / 4 steps
1
Create the initial long format data frame
Create a data frame called survey_data with these exact columns and values:
person with values 'Alice', 'Alice', 'Bob', 'Bob', 'Charlie', 'Charlie';
fruit with values 'Apple', 'Banana', 'Apple', 'Banana', 'Apple', 'Banana';
rating with values 5, 3, 4, 2, 3, 4.
R Programming
Need a hint?

Use data.frame() with vectors for each column named exactly as person, fruit, and rating.

2
Set the column to spread
Create a variable called fruit_column and set it to the string 'fruit' to specify the column that will become new columns in the wide format.
R Programming
Need a hint?

Just assign the string 'fruit' to the variable fruit_column.

3
Use pivot_wider to reshape the data
Use the pivot_wider function from the tidyr package to reshape survey_data into a wide format. Use id_cols = person, names_from = fruit_column, and values_from = rating. Save the result in a variable called wide_data. Make sure to load the tidyr package first.
R Programming
Need a hint?

Use library(tidyr) to load the package. Then call pivot_wider() with the correct arguments and assign to wide_data.

4
Print the wide format data
Print the variable wide_data to display the reshaped data frame.
R Programming
Need a hint?

Use print(wide_data) to show the reshaped data.