我不确定这是否必须使用我希望进行切换的整数值,或者我只是使用switch完全错误。状态是由1/0 / -1组成的向量。我的目标是用蓝色等替换1s ......
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
在我States
之前只有1或-1之前,这条线运作良好:
color_vertexFrame <- ifelse(States == 1, "blue", "red")
我现在想做的事只有3个值。
谢谢
答案 0 :(得分:3)
使用查找向量/表可能是最好的。以此示例数据为例:
States <- c(-1,1,0,0,1,-1)
选项1 - 命名向量:
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"
选项2 - 查找表
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"
答案 1 :(得分:1)
或使用@ 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