The melt() function from reshape package is used to convert data frame into wide format to long format in R. A long format data frame repeat values from first column and in wide format data frame does not repeat values from first column.
The following method shows how you can do it with syntax.
Method: Use melt() Function
library(reshape)
melt(dataframe,id="column_name")
The following example shows how to use melt() function in R.
Use melt() Function to ConvertData Frame to Long Format
Let’s see how we can convert data frame from wide format to long format using melt() function:
# Load library
library(reshape)
# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D"),Pressure=c(12.39,9.25,14.15,13.48),
Temperature=c(81,78,82,83))
# Show data frame
print(df)
# Convert data frame to long format
t <- melt(df,id="Machine_name")
# Show long format data frame
print(t)
Output:
Machine_name Pressure Temperature
1 A 12.39 81
2 B 9.25 78
3 C 14.15 82
4 D 13.48 83
Machine_name variable value
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
The output shows data frame in wide format and data frame after converting into long format.
You can rename the column names of long format data frame using names() function.The syntax for this function is names(long_dataframe) and assign new column names to it.
# Load library
library(reshape)
# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D"),Pressure=c(12.39,9.25,14.15,13.48),
Temperature=c(81,78,82,83))
# Convert data frame to long format
t <- melt(df,id="Machine_name")
# Rename column names of long format data frame
names(t) <- c("Machine","Inputs","Reading")
# Show long format data frame
print(t)
Output:
Machine Inputs 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
As the output shows data frame converted into long format also it column names are renamed.