Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement in R with integer values [duplicate]

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

like image 752
Simon Avatar asked Apr 30 '26 20:04

Simon


2 Answers

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" 
like image 118
thelatemail Avatar answered May 03 '26 14:05

thelatemail


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
like image 22
akrun Avatar answered May 03 '26 15:05

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!