You can transpose dataframe in R using two different methods.

The following methods show how you can do it with syntax.

Method 1: Use t() Function

t(df)

Method 2: Use transpose() Function from data.table Package

library(data.table)

transpose(df)

The following examples show how to use these function in R.

Use t() Function

Let’s see how we can use t() function to transpose the dataframe:

# Create dataframe
df <- data.frame(Start_date=as.Date(c("2000-05-21","1998-03-28","2001-01-19","2003-04-27","2004-11-26","2008-11-25")),
                 Machine_name = c("Machine1","Machine2","Machine3","Machine4","Machine5","Machine6"),
                 Value = c(108,120,135,95,98,105),Reading= c(110,97,91,89,80,85))

# Transpose dataframe
transpose_df <- t(df)

# Print transposed dataframe 
print(transpose_df) 

Output:

             [,1]         [,2]         [,3]         [,4]         [,5]         [,6]        
Start_date   "2000-05-21" "1998-03-28" "2001-01-19" "2003-04-27" "2004-11-26" "2008-11-25"
Machine_name "Machine1"   "Machine2"   "Machine3"   "Machine4"   "Machine5"   "Machine6"  
Value        "108"        "120"        "135"        " 95"        " 98"        "105"       
Reading      "110"        " 97"        " 91"        " 89"        " 80"        " 85" 

As we can see in the output dataframe is transpose successfully using t() function.

Use transpose() Function From data.table Package

Now let use transpose() function from data.table package:

library(data.table)

# Create dataframe
df <- data.frame(Machine_name = c("Machine1","Machine2","Machine3","Machine4","Machine5","Machine6"),
                 Value = c(108,120,135,95,98,105),Reading= c(110,97,91,89,80,85))

# Transpose dataframe
transpose_df <- transpose(df)

# Print transposed dataframe 
print(transpose_df) 

Output:

        V1       V2       V3       V4       V5       V6
1 Machine1 Machine2 Machine3 Machine4 Machine5 Machine6
2      108      120      135       95       98      105
3      110       97       91       89       80       85

In the above code we successfully transpose dataframe using transpose() function.

When we transpose the dataframe the column and rows are switch with each other.