Move a column to first position in a data frame

前端 未结 8 1522
别那么骄傲
别那么骄傲 2020-12-22 23:30

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 chan

8条回答
  •  萌比男神i
    2020-12-22 23:53

    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
    

提交回复
热议问题