logo

Swapping Rows and Columns in a Data Frame in R 📂R

Swapping Rows and Columns in a Data Frame in R

Overview

One of the strengths of R is that it makes some operations, which can be quite difficult for those familiar with other programming languages, easy to implement. For instance, it automatically expands memory when using arrays without having to allocate memory in advance, and operations like changing the value of a variable are very easy.

Example

20171120\_124856.png

Let’s swap the Sepal.Width column with the Species column in the Iris dataset. The method is too simple. Just assign the 5th column to the 2nd, and then the 2nd column to the 5th.

20171120\_133156.png

Of course, manipulating the position of rows is also possible in this manner.

Thus, these intuitive and convenient operations may be somewhat difficult to understand for those who are used to programming in other languages. Remembering how you had to create temporary variables and continuously move values around to change them might make R seem all the more attractive.