1

Asssume I have a list in R that looks as follows:

  partei   color
1 andere #636363
2    BDP #D0B100
3    CVP #FF8B07
4    EVP #65ECEF
5    FDP #5675D6
6    glp #77E599
7  Grüne #A3DD57
8     SP #CE2929
9    SVP #428953

I would like to order it according to this vector:

ps <- c("SVP", "SP", "FDP", "CVP", "Grüne", "glp", "BDP", "andere", "EVP")

I tried to order the list above using this code:

colors$partei <- factor(colors$partei, levels = ps)

However, this has no effect when I want get the colors out of the list in the correct order. I use this code to extract a vector of the colors:

farb <- as.vector(factor(rev(colors$color)))

I want the color vector to be in the same order as the psvector. Maybe the list colors should be converted to a data.frame, but I don't know how.

amonk
  • 1,769
  • 2
  • 18
  • 27
Mario
  • 2,393
  • 2
  • 17
  • 37
  • 2
    Have a look at `?match` – etienne Dec 02 '15 at 14:26
  • 3
    [Order a data frame's rows according to a target vector that specifies the desired order](http://stackoverflow.com/questions/11977102/order-a-data-frames-rows-according-to-a-target-vector-that-specifies-the-desire) – Henrik Dec 02 '15 at 14:34

1 Answers1

2

How about

ord <- sapply(ps, function(x) which(colors$partei == x))
farb <- colors$color[ord]
Felipe Gerard
  • 1,552
  • 13
  • 23