How to Reorder Columns of DataFrame in R

To reorder columns of a data frame in R, you can use the select() function from the dplyr package. For example, if you have a dataframe called df with columns A, B, and C, you can reorder them as C, A, and B using the df %>% select(C, A, B) expression.

Example

library(dplyr)

df <- data.frame(
  A = c(1, 2, 3),
  B = c("a", "b", "c"),
  C = c(TRUE, FALSE, TRUE),
  D = c(0.1, 0.2, 0.3)
)

df

cat("After reordering the columns of a data frame", "\n")

df_reorder <- df %>% select(D, A, C, B)

df_reorder

Output


   A  B  C     D
1  1  a TRUE  0.1
2  2  b FALSE 0.2
3  3  c TRUE  0.3

After reordering the columns of a data frame

   D    A   C    B
1  0.1  1  TRUE  a
2  0.2  2  FALSE b
3  0.3  3  TRUE  c

We created a dataframe df with four columns and then use the select() function from the dplyr package to reorder the columns as “D”, “A”, “C”, and “B” and stored the result in a new dataframe df_reorder.

Finally, it prints the original df and the reordered dataframes using the cat() function.

That’s it.

Leave a Comment