Filling or creating a named list using other lists

I have this ggplot graph that uses [fill] as aesthetic. To fix the colors of the fill categories (in the ggplot) I use

...
scale_fill_manual(values = fill_colors) +
...

and

fill_colors <- c(
"SCD" = "#FFC312",
"AD" = "#C4E538",
"FTD" = "#12CBC4",
"DLB" = "#FDA7DF",
"Psy" = "#006266"
)

Works like a charm.
Now I want to create the fill_colors list depending on the number of categories I read from my data file. From the data file I extract the categories: cats <- unique(datafile$category)
I also create a large enough color list:thecolors = c("#1abc9c", "#3498db", "#9b59b6", "#34495e", "#f1c40f", "#e67e22", "#c0392b", "#bdc3c7", "#d35400", "#273c75")
Question: how do I combine the cats list (not a fixed number of elements) with the color codes to a named list like 'fill_colors' that I can use in my ggplot?
So I end up with a named list which length is determined by the cats list and uses color codes starting at the first one.

How about:

cats <- c('SCD', 'AD', 'FTD', 'DLB', 'Psy')
fill_colors <- c('#FFC312', '#C4E538', '#12CBC4', '#FDA7DF', '#006266')
names(fill_colors) <- cats

If you want to start at the first color each time, then you don't need to do anything to your vector of colors. The plotting function will automatically grab only as many items as it needs from that vector.

To verify this behavior, try running this code:

library(tidyverse)

df1 <- data.frame(cats = LETTERS[1:3], vals = rpois(3, 10))
df2 <- data.frame(cats = LETTERS[1:5], vals = rpois(5, 10))

my_colors <- c("red", "orange", "yellow", "green", "blue")

df1 %>%
  ggplot(aes(x = cats, y = vals, fill = cats)) +
    geom_col() +
    scale_fill_manual(values = my_colors)

df2 %>%
  ggplot(aes(x = cats, y = vals, fill = cats)) +
    geom_col() +
    scale_fill_manual(values = my_colors)

Note, though, that if the number of items in cats exceeds the length of the vector of colors, you will get an error message. So just be sure you have at least as many colors as your maximum number of categories.

Yes! That did it. Thanks!!

If your question has been answered, even by yourself, please mark the solution. FAQ: How do I mark a solution?