Data Reshaping in R Programming

Generally, in R, data processing is done by taking data as an input from data frame where the data is organized into rows and columns. Data frames are mostly used since extracting data is much simpler and hence easier. But sometimes we need to reshape the format of the data frame from the one we receive. Hence, in R, we can split, merge  and reshape the data frame using various functions.

The various forms of reshaping data in a data frame are :

  • Transpose of a Matrix
  • Joining Rows and Columns
  • Merging of Data Frames
  • Melting and Casting

Why Data Reshaping is Important ?

While doing an analysis or using an analytic function, the resultant data obtained because of the experiment or study is generally different. The obtained data usually has one or more columns that correspond or identify a row followed by a number of columns that represent the measured values. We can say that these columns that identify a row can be the composite key of a column in a database.

Transpose of a Matrix

We can easily calculate the transpose of a matrix in R language with the help of t() function. The t() function takes a matrix or data frame as an input and gives the transpose of that matrix or data frame as it’s output.


t(Matrix/ Data frame)






# R program to find the transpose of a matrix
first <- matrix(c(1:12), nrow=4, byrow=TRUE)
print("Original Matrix")
first <- t(first)
print("Transpose of the Matrix")



[1] "Original Matrix"
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[4,]   10   11   12
[1] "Transpose of the Matrix"
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

Joining Rows and Columns in Data Frame

In R, we can join two vectors or merge two data frames using functions. There are basically two functions that perform these tasks: