# Load required libraries
library(tidyr) # For data reshaping functions
library(dplyr) # For data manipulation functions
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
# Create a simple long-format dataframe
data_long <- data.frame(
name = c("Alice", "Bob", "Alice", "Bob"),
subject = c("Math", "Math", "English", "English"),
score = c(90, 85, 95, 80)
)
# Display the original long-format data
print("Long format data:")
## [1] "Long format data:"
print(data_long)
## name subject score
## 1 Alice Math 90
## 2 Bob Math 85
## 3 Alice English 95
## 4 Bob English 80
# Use pivot_wider to transform the data from long to wide format
data_wide <- data_long %>%
pivot_wider(
names_from = subject, # Column whose values will become new column names
values_from = score # Column containing the values for the new columns
)
# Display the new wide-format data
print("\nWide format data:")
## [1] "\nWide format data:"
print(data_wide)
## # A tibble: 2 × 3
## name Math English
## <chr> <dbl> <dbl>
## 1 Alice 90 95
## 2 Bob 85 80