0

I am trying to use the relocate() function to reorder the columns of a dataframe based on a specific order. The order is not alphabetical. E.g.

Red Yellow Green Brown Blue Pink Black White

The data could be different each time it is loaded in. For example, it might be as follows (with no column for Blue):

Black Brown Green Pink Red White Yellow
6 5 2 1 3 8 2

When I try to relocate based on the full ordered listing, e.g.

df %>% relocate("Red", "Yellow", "Green", "Brown", "Blue", "Pink", "Black", "White")

I then get the following error:

Error in relocate(): ! Can't subset columns that don't exist. ✖ Column Blue doesn't exist.

I don't want to specifically list the dataframe as I don't know what columns will/won't be included each time. Is there a way to order the column based on the full list even if some column names are missing?

stefan
  • 90,330
  • 6
  • 25
  • 51

1 Answers1

3

You could use any_of:

df <- data.frame(
  Black = c(6L),
  Brown = c(5L),
  Green = c(2L),
  Pink = c(1L),
  Red = c(3L),
  White = c(8L),
  Yellow = c(2L)
)

library(dplyr)

df %>% 
  relocate(any_of(c("Red", "Yellow", "Green", "Brown", "Blue", "Pink", "Black", "White")))
#>   Red Yellow Green Brown Pink Black White
#> 1   3      2     2     5    1     6     8
stefan
  • 90,330
  • 6
  • 25
  • 51