change the order of columns in r

You can change the order of columns in R with the help of dplyr package from the tidyverse library. Here's an example:

Let's say you have a data frame df with columns in the following order: "name", "age", "gender".

main.r
library(dplyr)

# Create a sample data frame
df <- data.frame(name = c("John", "Jane", "Bob"),
                 age = c(25, 30, 35),
                 gender = c("Male", "Female", "Male"))

# Print the original data frame
df
224 chars
10 lines
main.r
   name age gender
1  John  25   Male
2  Jane  30 Female
3   Bob  35   Male
76 chars
5 lines

To change the order of columns in R, you can use the select() function from dplyr and specify the new order of the columns using their names:

main.r
# Change the order of columns
df_new <- select(df, gender, age, name)

# Print the updated data frame
df_new
109 chars
6 lines
main.r
  gender age name
1   Male  25 John
2 Female  30 Jane
3   Male  35  Bob
72 chars
5 lines

As you can see, the order of columns in the new data frame df_new is now "gender", "age", "name".

gistlibby LogSnag