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".
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.
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With