Simon
Simon

Reputation: 1

How to convert data frame with colors to a character list in r

I have a data frame that contains color codes for different actors (two variables: var1 = "actor" and var2 = "color"). I would like to turn this data frame into a character list that entails the color code for each actor. Does anyone have an idea how to do this?

Sample data frame:

actor <- c('CDU','SPD','Greens', 'FDP')
color <- c('#000000', '#FF0000', '#009500', '#FFFF00')
df <- data.frame(actor, color)

df
actor color
1 CDU #000000
2 SPD #FF0000
3 Greens #009500
4 FDP #FFFF00

What I want is a character list I can create manually like this:

actor_color <- c('CDU' = '#000000',
             'SPD' = '#FF0000',
             'Greens'= '#009500',
             'FDP' = '#FFFF00')

Upvotes: 0

Views: 143

Answers (1)

Colin H
Colin H

Reputation: 660

Just use the setNames function to apply the names to your list of colors as below:

l <- setNames(df$color, df$actor)
> print(l)
      CDU       SPD    Greens       FDP 
"#000000" "#FF0000" "#009500" "#FFFF00" 

Upvotes: 1

Related Questions