0
0
R Programmingprogramming~30 mins

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

Choose your learning style9 modes available
Convert Wide Data to Long Format using pivot_longer
📖 Scenario: You have a small dataset showing sales of different fruits in two months. The data is in a wide format, where each month is a separate column.We want to change this data into a long format, where each row shows the fruit, the month, and the sales amount. This format is easier to analyze and plot.
🎯 Goal: Transform the wide data frame fruit_sales into a long format using pivot_longer from the tidyr package. The result should have columns Fruit, Month, and Sales.
📋 What You'll Learn
Create a data frame called fruit_sales with columns Fruit, Jan, and Feb and the exact data provided.
Create a vector called months containing the column names Jan and Feb.
Use pivot_longer on fruit_sales with cols = months, naming the new columns Month and Sales.
Print the resulting long format data frame.
💡 Why This Matters
🌍 Real World
Data often comes in wide format from spreadsheets or reports. Converting it to long format helps in analysis and visualization.
💼 Career
Data analysts and scientists frequently reshape data using pivot_longer to prepare datasets for plotting and statistical modeling.
Progress0 / 4 steps
1
Create the wide data frame
Create a data frame called fruit_sales with columns Fruit, Jan, and Feb containing these exact rows: 'Apple', 30, 45, 'Banana', 25, 40, 'Cherry', 15, 20.
R Programming
Need a hint?

Use data.frame() with vectors for each column named exactly Fruit, Jan, and Feb.

2
Create a vector of month columns
Create a character vector called months containing the strings 'Jan' and 'Feb'.
R Programming
Need a hint?

Use c() to create a vector with the two month names as strings.

3
Use pivot_longer to reshape the data
Use pivot_longer from the tidyr package on fruit_sales with cols = months, names_to = 'Month', and values_to = 'Sales'. Save the result in a variable called long_sales. Remember to load tidyr first.
R Programming
Need a hint?

Use library(tidyr) to load the package. Then use pivot_longer() with the exact arguments.

4
Print the long format data frame
Write a line to print the variable long_sales.
R Programming
Need a hint?

Use print(long_sales) to display the transformed data.