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?