★ [학습목표]
행렬 데이터를 cast, melt 함수를 이용하여 transpose 할 수 있다.
# Install and load the reshape2 package
install.packages("reshape2")
library(reshape2)
# Create a sample data frame
data <- data.frame(
ID = c(1, 2, 3, 1, 2, 3),
Category = c("A", "A", "A", "B", "B", "B"),
Value = c(10, 20, 30, 40, 50, 60)
)
# Print the original data frame
print("Original data frame:")
print(data)
# Reshape the data from long to wide format using dcast
wide_data <- dcast(data, ID ~ Category, value.var = "Value")
# Print the reshaped data frame
print("Reshaped data frame:")
print(wide_data)

dt_1 <- wide_data
dt_1
dt_1[,c(1,3,2)]

# Install and load the reshape2 package
install.packages("reshape2")
library(reshape2)
# Create a sample wide-format data frame
wide_data <- data.frame(
ID = c(1, 2, 3),
A = c(10, 20, 30),
B = c(40, 50, 60),
C = c(70, 80, 90)
)
# Print the original wide-format data frame
print("Original wide-format data frame:")
print(wide_data)
# Melt the wide-format data frame into long format using melt
long_data <- melt(wide_data, id.vars = "ID")
# Print the melted long-format data frame
print("Melted long-format data frame:")
print(long_data)
