Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reordering columns in a large dataframe

Tags:

r

Using the following example dataframe:

a <-  c(1:5) b <- c("Cat", "Dog", "Rabbit", "Cat", "Dog") c <- c("Dog", "Rabbit", "Cat", "Dog", "Dog") d <- c("Rabbit", "Cat", "Dog", "Dog", "Rabbit") e <- c("Cat", "Dog", "Dog", "Rabbit", "Cat") f <- c("Cat", "Dog", "Dog", "Rabbit", "Cat")  df <- data.frame(a,b,c,d,e,f) 

I want to investigate how to reorder the columns WITHOUT having to type in all the column names, i.e., df[,c("a","d","e","f","b","c")]

How would I just say I want columns b and c AFTER column f? (only referencing the columns or range of columns that I want to move?).

Many thanks in advance for your help.

like image 708
KT_1 Avatar asked Aug 20 '13 15:08

KT_1


People also ask

How do I reorder columns in a data frame?

You need to create a new list of your columns in the desired order, then use df = df[cols] to rearrange the columns in this new order.

Which function is used to rearrange columns in Dataframe?

order() is used to rearrange the dataframe columns in alphabetical order.

How do I change the order of Dataframe columns in pandas?

You can change the order of columns in the pandas dataframe using the df. reindex() method.

How do I move multiple columns in pandas?

Just use double brackets and insert the columns you want to shift.


1 Answers

To move specific columns to the beginning or end of a data.frame, use select from the dplyr package and its everything() function. In this example we are sending to the end:

library(dplyr) df %>%   select(-b, -c, everything())    a      d      e      f      b      c 1 1 Rabbit    Cat    Cat    Cat    Dog 2 2    Cat    Dog    Dog    Dog Rabbit 3 3    Dog    Dog    Dog Rabbit    Cat 4 4    Dog Rabbit Rabbit    Cat    Dog 5 5 Rabbit    Cat    Cat    Dog    Dog 

Without the negation, the columns would be sent to the front.

like image 88
Sam Firke Avatar answered Sep 20 '22 15:09

Sam Firke