Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a column to first position in a data frame

Tags:

dataframe

r

I would like to have the last column of the data frame moved to the start (as first column). How can I do it in R?

My data.frame has about a thousand columns to changing the order wont to. I just want to pick one column and "move it to the start".

like image 644
ECII Avatar asked Mar 09 '14 18:03

ECII


People also ask

How do I change the position of a column 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.

How do I add a column to the first position in a Dataframe?

Answer. Yes, you can add a new column in a specified position into a dataframe, by specifying an index and using the insert() function. By default, adding a column will always add it as the last column of a dataframe. This will insert the column at index 2, and fill it with the data provided by data .

How do I move a column to the front of a Dataframe in R?

To move a column to first in the dataframe, we use relocate() with the column name we want to move. This will move the column of interest to the first column. We can also move the column of interest to a location after another column in the dataframe.

How do you change the position of a column?

Press and hold the Shift key, and then drag the column to a new location. You will see a faint "I" bar along the entire length of the column and a box indicating where the new column will be moved. That's it! Release the mouse button, then leave the Shift key and find the column moved to a new position.


1 Answers

Dplyr's select() approach

Moving the last column to the start:

new_df <- df %>%   select(last_column_name, everything()) 

This is also valid for any column and any quantity:

new_df <- df %>%   select(col_5, col_8, everything()) 

Example using mtcars data frame:

head(mtcars, n = 2) #                    mpg cyl disp  hp drat    wt  qsec vs am gear carb # Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 # Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4  # Last column is 'carb' new_df <- mtcars %>% select(carb, everything())  head(new_df, n = 2) #                   carb  mpg cyl disp  hp drat    wt  qsec vs am gear # Mazda RX4            4 21.0   6  160 110 3.90 2.620 16.46  0  1    4 # Mazda RX4 Wag        4 21.0   6  160 110 3.90 2.875 17.02  0  1    4 
like image 177
marc_aragones Avatar answered Sep 23 '22 19:09

marc_aragones