3

I am not sure whether this has to do something with integer values by which I want to do the switch or I am just using switch entirely wrong. States is vector consisting of 1 / 0 / -1. My goal is to replace 1s with blue, etc...

color_vertexFrame <- switch( States, 
                                  1 <- "blue",
                                  0 <- "grey",
                                 -1 <- "red")

Error in switch(States, 1 <- "blue", 0 <- "grey", -1 <- "red") : 
    EXPR must be a length 1 vector

Before I had in States only 1 or -1 so this line worked well :

color_vertexFrame <- ifelse(States == 1, "blue", "red")

I would like to do now something similar only with 3 values.

Thank you

Simon
  • 242
  • 2
  • 3
  • 13

2 Answers2

3

Using a lookup vector/table may be best here. Take this example data:

States <- c(-1,1,0,0,1,-1)

Option 1 - named vector:

cols <- setNames(c("blue","grey","red"),c(1,0,-1))
cols[as.character(States)]
#    -1      1      0      0      1     -1 
# "red" "blue" "grey" "grey" "blue"  "red" 

Option 2 - lookup table

coldf <- data.frame(cols=c("blue","grey","red"),val=c(1,0,-1),
                    stringsAsFactors=FALSE)
coldf$cols[match(States,coldf$val)]
#[1] "red"  "blue" "grey" "grey" "blue" "red" 
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • Isn't there some elegant one line command for this ? Or there is, but it isn't efficient ? – Simon Aug 07 '14 at 03:14
  • @Simon - there may be - if I had bothered to search first, I would have found I have answered this before and even done benchmarks on some options - see the duplicates. – thelatemail Aug 07 '14 at 03:21
  • Thank you, your other post is quite helpful. Sorry for duplicate, I haven't found it probably because I was trying to use switch... – Simon Aug 07 '14 at 03:25
1

Or using @thelatemail's States

 cut(States, breaks=c(-Inf,-1,0,1), labels=c("red", "grey", "blue"))
 #[1] red  blue grey grey blue red 
 #Levels: red grey blue
akrun
  • 874,273
  • 37
  • 540
  • 662