r - reorder columns in data frame

To reorder columns in a data frame in R, you can use the indexing operator [ ] or the select() function from the dplyr package. Here are the steps to do it:

Step 1: Create a Data Frame

First, create a data frame with multiple columns. You can either create a new data frame or use an existing one. For example, let's create a data frame with three columns: "Name", "Age", and "Gender".

# Create a data frame
df <- data.frame(Name = c("John", "Jane", "Mike"),
                 Age = c(25, 30, 35),
                 Gender = c("Male", "Female", "Male"))

Step 2: Reorder Columns Using Indexing Operator

To reorder the columns using the indexing operator [ ], specify the desired order of column names inside the square brackets. For example, if you want to reorder the columns as "Age", "Name", and "Gender", you can do the following:

# Reorder columns using indexing operator
df <- df[, c("Age", "Name", "Gender")]

Step 3: Reorder Columns Using select() Function

Alternatively, you can use the select() function from the dplyr package to reorder the columns. The select() function allows you to select and reorder columns by their names. Here's an example:

# Reorder columns using select() function
library(dplyr)
df <- select(df, Age, Name, Gender)

In this example, the select() function is used to select the columns "Age", "Name", and "Gender" in the specified order.

That's it! You have now reordered the columns in the data frame.