调试条件If链

时间:2013-11-28 11:06:47

标签: r conditional-statements scatter-plot chain

我正在尝试创建一个散点图,并以不同方式为指定范围内的点着色。我觉得好像这条链应该起作用,我在括号中陈述条件和所需的颜色。

我的方法中是否有人发现错误?或者可能是语法?

plot(x, y, xlab="chr X position (Mb)",
     ylab="Diversity", pch=16, cex=0.7,
     col=if(x < 4), {"red"}
          else {
            if((x>3)&(x<89)) {"black"}
            else {
              if((x>88)&(x<94)) {"blue"}
              }
            else {
              if((x>93)&(x<155)) {"black"}
              }
            else {
              if(x>154) {"purple"}
              }
            }

2 个答案:

答案 0 :(得分:4)

你的代码太丑了!使用cut将数值转换为分类“因子”对象,然后设置颜色。

> x=sample(1:20)
> x
 [1]  5  1  9 17  2  6  4  3  8 13 16 10 11 20 18 19 12 14  7 15
> f = cut(x,breaks=c(0,5,13,21)) # choose your breaks here
> f
 [1] (0,5]   (0,5]   (5,13]  (13,21] (0,5]   (5,13]  (0,5]   (0,5]   (5,13] 
[10] (5,13]  (13,21] (5,13]  (5,13]  (13,21] (13,21] (13,21] (5,13]  (13,21]
[19] (5,13]  (13,21]
Levels: (0,5] (5,13] (13,21]
> levels(f)=c("red","green","purple")
> plot(x,col=as.character(f),pch=19)

那应该绘制红色的低点,绿色的中间,紫色的顶部。

对于额外的点,编写一个函数,它可以获取您的值,中断和颜色矢量,并为您进行颜色映射。然后你就做了:

> plot(x, col=colourMap(x,breaks = c(0,5,13,21), colours = c("red","green","purple")))

答案 1 :(得分:1)

以下是使用ifelse

的解决方案
col = ifelse(x<4, "red",
       ifelse(x>3 & x<89 | x>93 & x<155, "black",
              ifelse(x>88 & x<94, "blue", "purple")))

您需要ifelse因为ifelse已经过矢量化,if不是,因此ifelse会检查矢量中的每个元素并填充相应的颜色,而if 1}}仅检查第一个元素。

需要注意的一个简单示例:

x <- 1:6  # a sample vector

# using `if` to check condition and assigning a value, it'll fail 
if(x<4){
  "red"
} else {
  "other color"
}

# suing `ifelse` for the same task. It'll win
ifelse(x<4, "red", "other color")

来自帮助文件

  

ifelse返回一个与填充的test相同形状的值   选择是或否的元素取决于是否   测试元素为TRUE或FALSE