Switch statement in R with integer values

I'm not sure if this is supposed to do anything with the integer values ​​over which I want to make the switch, or just using the switch completely wrong. States are a vector 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 was at States

only 1 or -1, this line worked well:

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

      

Now I would like to do something like this with only 3 values.

thank

+3


source to share


2 answers


Using a lookup vector / table might be best here. Take the 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" 

      

+3


source


Or using @thelatemail 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

      

+1


source







All Articles