Example for dcast() function in R
This is a basic example of how to use the dcast()
function to reshape data from long to wide format in R.
# Load the reshape2 package
library(reshape2)
# Sample data in long format
data_long <- data.frame(
ID = c(1, 1, 2, 2),
Time = c("T1", "T2", "T1", "T2"),
Value = c(10, 15, 20, 25)
)
# Display the long format data
print("Data in long format:")
print(data_long)
# Cast the data from long to wide format using dcast
data_wide <- dcast(data_long, ID ~ Time, value.var = "Value")
# Display the wide format data
print("Data in wide format:")
print(data_wide)
Output:
[1] "Data in long format:"
ID Time Value
1 1 T1 10
2 1 T2 15
3 2 T1 20
4 2 T2 25
[1] "Data in wide format:"
ID T1 T2
1 1 10 15
2 2 20 25
dcast() Function in R
Reshaping data in R Programming Language is the process of transforming the structure of a dataset from one format to another. This transformation is done by the dcast function in R.