The cast() function from reshape2 package is used to reshape dataframes. This cast() function convert dataframe from long format to wide format. The wide format having values that does not repeat in first column and long format contains values that contain repeat values in first column.

The following method shows how you can do it with syntax.

Method 1: Use cast() Function

library(reshape2)

cast(df, column1 ~ column2)

The following example shows how to use cast() function in R.

Using cast() Function

Let’s see how to use cast() function in R to convrt dataframe from long format to wide format:

# Load package
library(reshape2)

# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","A","B","C","D"),
                 Variable=c("Pressure","Pressure","Pressure","Pressure","Temperature","Temperature","Temperature","Temperature"),
                 Reading=c(12.39,9.25,14.15,13.48,81,78,82,83))

# Show dataframe
print(df)

# Convert dataframe from long format to wide format
t <- dcast(df, Machine_name ~ Variable)

# Show wide format dataframe
print(t)            

Output:

 Machine_name    Variable Reading
1            A    Pressure   12.39
2            B    Pressure    9.25
3            C    Pressure   14.15
4            D    Pressure   13.48
5            A Temperature   81.00
6            B Temperature   78.00
7            C Temperature   82.00
8            D Temperature   83.00


 Machine_name Pressure Temperature
1            A    12.39          81
2            B     9.25          78
3            C    14.15          82
4            D    13.48          83

Here the output shows wide format of dataframe which convert using cast() function.