library(tidyr)
  library(dplyr)
## 
## 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
#Hàm gather(): Chuyển dữ liệu từ dạng rộng sang dạng dài.

data <- data.frame(
  student = c("Alice", "Bob", "Charlie"),
  math = c(85, 72, 90),
  science = c(92, 88, 78),
  history = c(78, 85, 92)
)

print(data)
##   student math science history
## 1   Alice   85      92      78
## 2     Bob   72      88      85
## 3 Charlie   90      78      92
# Chuyển từ dạng rộng sang dạng dài

gathered_data <- data %>% 
  gather(key = "subjects", value="score", -student)

print(gathered_data)
##   student subjects score
## 1   Alice     math    85
## 2     Bob     math    72
## 3 Charlie     math    90
## 4   Alice  science    92
## 5     Bob  science    88
## 6 Charlie  science    78
## 7   Alice  history    78
## 8     Bob  history    85
## 9 Charlie  history    92
#Hàm spread(): Chuyển dữ liệu từ dạng dài sang dạng rộng.
spread_data <- gathered_data %>% 
  spread(key="subjects", value = "score")

print(spread_data)
##   student history math science
## 1   Alice      78   85      92
## 2     Bob      85   72      88
## 3 Charlie      92   90      78