Moving columns in R with relocate

The relocate() function is a simple but very useful function from the Tidyverse. It allows you to move the position with columns within a data frame. I use this most often where I have been delivered data that is not presented in a logical column order, particularly if I am going to be using the select() function to select ranges of columns like in my example below.


Subscribe below to get updates on my latest videos, courses, and other useful information.


library(tidyverse)

mydata<-data.frame(stringsAsFactors = TRUE,
             Class = c("A", "A", "A", "A", "B", "B", "B", "B"),
                Q1 = c(5, 3, 4, 4, 6, 3, 2, 1),
                Q3 = c(4, 5, 3, 1, 2, 3, 4, 5),
                Q4 = c(4, 2, 4, 5, 3, 5, 6, 5),
                Q5 = c(2, 1, 2, 1, 2, 3, 2, 3),
                Q2 = c(2, 2, 3, 6, 5, 1, 3, 2),
            Gender = c("M", "F", "X", "M", "F", "X", "M", "F"),
             State = c("VIC", "VIC", "VIC", "NSW", "NSW", "QLD", "QLD", "QLD"))

# Why might I want to rearrange? Important for larger sets if selecting like this
mydata %>% select(Q1:Q5)

# Fixing position of Q2
newdata <- mydata %>% relocate(Q2, .after=Q1)
mydata %>% relocate(Q2, .before=Q3)

# Move Gender variable to first column
mydata %>% relocate(Gender)

# Move Gender and State to first two columns
mydata %>% relocate(Gender, State)