R,ifelse只返回一个值

时间:2014-01-04 18:53:28

标签: r if-statement

我有一个如下数据框。

test <- data.frame (myrank = c(0.9629,0.1296), poster = c("dial","bear"))
test
##  myrank poster
## 1 0.9629   dial
## 2 0.1296   bear

我有ifelse函数如下所示,但它只返回一个值,我无法弄清楚原因。

color <- function (x){
    x$colorchip <- ifelse((((x$myrank> 0) | (x$myrank= 0)) & x$myrank < 0.143),
                          "#FF0000",
                          ifelse((x$myrank > 0.143 & x$myrank < 0.286),
                                 "#FF1919",
                                 ifelse((x$myrank > 0.286 & x$myrank < 0.428571),
                                        "#FF3333",
                                        ifelse((x$myrank > 0.428571 & x$myrank < 0.571429),
                                               "#FFFFFF",
                                               ifelse((x$myrank > 0.571429 & x$myrank < 0.714286),
                                                      "#3333D6",
                                                      ifelse((x$myrank > 0.714286 & x$myrank < 0.857143),
                                                             "#1919D1",
                                                             "#0000CC"
                                                      ))))))
    return(x$colorchip)
}


color(test)
## [1] "#FF0000" "#FF0000"

我不确定我在这里缺少什么。任何建议将不胜感激!

1 个答案:

答案 0 :(得分:8)

@MarkHeckmann已经确定了您的具体问题,但我建议使用此功能:

color <- function (x){
     cols <- c("#FF0000","#FF1919","#FF3333",
               "#FFFFFF","#3333D6","#1919D1",
               "#0000CC")
     i <- findInterval(x,c(0,0.143,0.286,0.428571,0.571429,
                             0.714286,0.857143,Inf))
     cols[i]
 }
 test <- data.frame (myrank = c(0.9629,0.1296),
                     poster = c("dial","bear"))
 color(test$myrank)
 ## "#0000CC" "#FF0000"

如果用(0:7)/7替换了分界点,您的代码可能会更容易阅读。您可能还会发现?colorRamp函数很有用......