Home » How to Switch Two Columns in R (With Examples)

How to Switch Two Columns in R (With Examples)

by Erma Khan
spot_img

Occasionally you may want to switch the position of two columns in an R data frame. Fortunately this is easy to do using one of the two following bits of code:

Option 1: Use column syntax.

#define order of data frame columns
df 

Option 2: Use row and column syntax.

#define order of data frame columns
df 

The following examples illustrate how to use these two bits of code in practice.

Example 1: Switch Two Columns Using Column Syntax

The following code shows how to create a data frame with four columns and then switch the position of the first and third column:

#create data frame
df #view data frame
df

  col1 col2 col3 col4
1    1    4    7    9
2    2    4    7    9
3    6    5    8    9
4    3    4    7    5
5    6    3    3    5
6    6    2    3    3

#switch positions of first and third column
df #view new data frame
df

  col3 col2 col1 col4
1    7    4    1    9
2    7    4    2    9
3    8    5    6    9
4    7    4    3    5
5    3    3    6    5
6    3    2    6    3

Example 2: Switch Two Columns Using Row & Column Syntax

The following code shows how to create a data frame with four columns and then switch the position of the first and third column:

#create data frame
df #view data frame
df

  col1 col2 col3 col4
1    1    4    7    9
2    2    4    7    9
3    6    5    8    9
4    3    4    7    5
5    6    3    3    5
6    6    2    3    3

#switch positions of first and third column
df #view new data frame
df

  col3 col2 col1 col4
1    7    4    1    9
2    7    4    2    9
3    8    5    6    9
4    7    4    3    5
5    3    3    6    5
6    3    2    6    3

Notice that both methods lead to the same results.

Additional Resources

How to Sum Specific Columns in R
How to Average Across Columns in R

spot_img

Related Posts