• Skip to secondary menu
  • Skip to main content
  • Skip to primary sidebar

Python and R Tips

Learn Data Science with Python and R

  • Home
  • Python
  • Pandas
    • Pandas 101
  • tidyverse
    • tidyverse 101
  • R
  • Linux
  • Conferences
  • Python Books
  • About
    • Privacy Policy
You are here: Home / R / tidyverse 101 / How To Move A Column to the Front with dplyr

How To Move A Column to the Front with dplyr

October 30, 2020 by cmdlinetips

In this post we will learn how to change column order or move a column in R with dplyr. More specifically, we will learn how to move a single column of interest to first in the dataframe, before and after a specific column in the dataframe. We will use relocate() function available in dplyr version 1.0.0 to change the column position. And we will also see an example of moving a column to the front when working with dplyr version earlier than 1.0.0.

Let us load tidyverse first.

library("tidyverse")

As in other tidyverse 101 examples, we will use the fantastic Penguins dataset to illustrate the three ways to see data in a dataframe. Let us load the data from cmdlinetips.com’ github page.

path2data <- "https://raw.githubusercontent.com/cmdlinetips/data/master/palmer_penguins.csv"
penguins<- readr::read_csv(path2data)

Note that the last column in the data frame is sex column.

## Parsed with column specification:
## cols(
##   species = col_character(),
##   island = col_character(),
##   bill_length_mm = col_double(),
##   bill_depth_mm = col_double(),
##   flipper_length_mm = col_double(),
##   body_mass_g = col_double(),
##   sex = col_character()
## )

First, we will see how to move a column to first in the dataframe. To move a column to first in the dataframe, we use relocate() with the column name we want to move.

penguins %>% 
  relocate(sex)

This will move the column of interest to the first column.

## # A tibble: 344 x 7
##    sex   species island bill_length_mm bill_depth_mm flipper_length_…
##    <chr> <chr>   <chr>           <dbl>         <dbl>            <dbl>
##  1 male  Adelie  Torge…           39.1          18.7              181
##  2 fema… Adelie  Torge…           39.5          17.4              186
##  3 fema… Adelie  Torge…           40.3          18                195
##  4 <NA>  Adelie  Torge…           NA            NA                 NA
##  5 fema… Adelie  Torge…           36.7          19.3              193
##  6 male  Adelie  Torge…           39.3          20.6              190
##  7 fema… Adelie  Torge…           38.9          17.8              181
##  8 male  Adelie  Torge…           39.2          19.6              195
##  9 <NA>  Adelie  Torge…           34.1          18.1              193
## 10 <NA>  Adelie  Torge…           42            20.2              190
## # … with 334 more rows, and 1 more variable: body_mass_g <dbl>

We can also move the column of interest to a location after another column in the dataframe. In this example, we move the column “sex” to position after “species” column.

penguins %>% 
  relocate(sex, .after=species)

Notice that now the sex column is second column after the species.

## # A tibble: 344 x 7
##    species sex   island bill_length_mm bill_depth_mm flipper_length_…
##    <chr>   <chr> <chr>           <dbl>         <dbl>            <dbl>
##  1 Adelie  male  Torge…           39.1          18.7              181
##  2 Adelie  fema… Torge…           39.5          17.4              186
##  3 Adelie  fema… Torge…           40.3          18                195
##  4 Adelie  <NA>  Torge…           NA            NA                 NA
##  5 Adelie  fema… Torge…           36.7          19.3              193
##  6 Adelie  male  Torge…           39.3          20.6              190
##  7 Adelie  fema… Torge…           38.9          17.8              181
##  8 Adelie  male  Torge…           39.2          19.6              195
##  9 Adelie  <NA>  Torge…           34.1          18.1              193
## 10 Adelie  <NA>  Torge…           42            20.2              190
## # … with 334 more rows, and 1 more variable: body_mass_g <dbl>

Similarly we can also specify the location to be after another column present in the dataframe. In this example, we move sex column to be relocated after “bill_length_mm”.

penguins %>% 
  relocate(sex, .before=bill_length_mm)
## # A tibble: 344 x 7
##    species island sex   bill_length_mm bill_depth_mm flipper_length_…
##    <chr>   <chr>  <chr>          <dbl>         <dbl>            <dbl>
##  1 Adelie  Torge… male            39.1          18.7              181
##  2 Adelie  Torge… fema…           39.5          17.4              186
##  3 Adelie  Torge… fema…           40.3          18                195
##  4 Adelie  Torge… <NA>            NA            NA                 NA
##  5 Adelie  Torge… fema…           36.7          19.3              193
##  6 Adelie  Torge… male            39.3          20.6              190
##  7 Adelie  Torge… fema…           38.9          17.8              181
##  8 Adelie  Torge… male            39.2          19.6              195
##  9 Adelie  Torge… <NA>            34.1          18.1              193
## 10 Adelie  Torge… <NA>            42            20.2              190
## # … with 334 more rows, and 1 more variable: body_mass_g <dbl>

In this post, we saw how to move a single column to first and before or after another column. dplyr’s relocate() is versatile and can conditions as input to move multiple columns at the same time. Check out soon for more examples of using dplyr’s relocate().

How to Move a Column to the Front with dplyr version earlier to dplyr 1.0?

Note that the relocate() function is new in dplyr 1.0.0. If you are working with dplyr version earlier than 1.0.0, we can use select() and everything() function as follows to move a specific column to the front.

penguins %>% 
  select(sex, everything())

This approach also work with moving selected to column(s) to the last column with the negative sign. For example to to move a column to the last column in the dataframe, we use

penguins %>% 
  select(-sex, everything())

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Related posts:

How To Remove Rows With Missing Values with dplyr's drop_na()?How To Remove Rows with Missing values using dplyr Default Thumbnaildplyr filter(): Filter/Select Rows based on conditions Default Thumbnaildplyr groupby() and summarize(): Group By One or More Variables Default Thumbnaildplyr mutate(): Create New Variables with mutate

Filed Under: dplyr relocate(), tidyverse 101 Tagged With: Move a column to front, R

Reader Interactions

Trackbacks

  1. How To Remove Rows with Missing values using dplyr? - Python and R Tips says:
    October 31, 2020 at 10:40 pm

    […] Let us move sex column which has a number of missing values to the front using dplyr’s relocate() function. […]

  2. How to Make Time-Series Plot with Rolling Mean in R? - Data Viz with Python and R says:
    November 10, 2020 at 8:11 pm

    […] our convenience, we have moved the seven day rolling average to first column in the […]

Primary Sidebar

Subscribe to Python and R Tips and Learn Data Science

Learn Pandas in Python and Tidyverse in R

Tags

Altair Basic NumPy Book Review Data Science Data Science Books Data Science Resources Data Science Roundup Data Visualization Dimensionality Reduction Dropbox Dropbox Free Space Dropbox Tips Emacs Emacs Tips ggplot2 Linux Commands Linux Tips Mac Os X Tips Maximum Likelihood Estimation in R MLE in R NumPy Pandas Pandas 101 Pandas Dataframe Pandas Data Frame pandas groupby() Pandas select columns Pandas select_dtypes Python Python 3 Python Boxplot Python Tips R rstats R Tips Seaborn Seaborn Boxplot Seaborn Catplot Shell Scripting Sparse Matrix in Python tidy evaluation tidyverse tidyverse 101 Vim Vim Tips

RSS RSS

  • How to convert row names to a column in Pandas
  • How to resize an image with PyTorch
  • Fashion-MNIST data from PyTorch
  • Pandas case_when() with multiple examples
  • An Introduction to Statistical Learning: with Applications in Python Is Here
  • 10 Tips to customize ggplot2 title text
  • 8 Plot types with Matplotlib in Python
  • PCA on S&P 500 Stock Return Data
  • Linear Regression with Matrix Decomposition Methods
  • Numpy’s random choice() function

Copyright © 2025 · Lifestyle Pro on Genesis Framework · WordPress · Log in

Go to mobile version