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