R Data Reshaping

Facebooktwitterredditpinterestlinkedinmailby feather

In R programming, data reshaping is the process of changing the way data is organized into rows and columns.

Most of the time data processing is done by taking the input data as a data frame.

Sometimes we need data frame in a different format. R provides many functions to split, merge and change the rows to columns and vice-versa in data frame.

Joining Columns and Rows in a Data Frame

cbind()

Syntax:

Here, x1 and x2 may be a data frame, matrix or vector.

We use cbind() function to merge vector, matrix or data frame by columns.

Example:

Output:

rbind()

rbind() function is used to combine vector, matrix or data frame by rows:

Syntax:

Here, x1 and x2 may be a data frame, matrix or vector.

Example:

Output:

Merging Data Frame

We can merge two data or more frames by using the merge() function. It is similar to join of SQL. Here, both data frames must have at least one common column by which we can join them.

Example:

Let’s see an example to merge two data frames by roll_no:

Output:

Transpose

We can transpose a matrix or data frame by using t() function.

Example:

Output:

Melting and Casting

We can reshape the data into multiple steps in order to convert input data into the required format.

We generally melt data so that each row in converted into the unique id-variable combination. Then we cast this data into the desired format. The function used to do this are melt() function and cast() function.

melt()

Example:

Output:

cast()

Example:

Let’s cast the melted data to evaluate mean:

Output:

Refernce:
https://data-flair.training/blogs/r-data-reshaping-function-package/

Facebooktwitterredditpinterestlinkedinmailby feather