Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

r - Move a column to first position in a data frame

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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...