How to Switch Two Columns in R (With Examples)


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 <- df[c("col1", "col2", "col3", "col4")]

Option 2: Use row and column syntax.

#define order of data frame columns
df <- df[ , c("col1", "col2", "col3", "col4")]

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 <- data.frame(col1=c(1, 2, 6, 3, 6, 6),
                 col2=c(4, 4, 5, 4, 3, 2),
                 col3=c(7, 7, 8, 7, 3, 3),
                 col4=c(9, 9, 9, 5, 5, 3))

#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 <- df[c("col3", "col2", "col1", "col4")]

#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 <- data.frame(col1=c(1, 2, 6, 3, 6, 6),
                 col2=c(4, 4, 5, 4, 3, 2),
                 col3=c(7, 7, 8, 7, 3, 3),
                 col4=c(9, 9, 9, 5, 5, 3))

#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 <- df[ , c("col3", "col2", "col1", "col4")]

#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

Leave a Reply

Your email address will not be published.