在带有else但不在if语句中的语句中出现r错误

时间:2016-01-14 20:08:03

标签: r if-statement

我的数据集包含带小数的数值

当我写这样一个简单的if语句时:

data$Segment <- ifelse(data$RankAll> 10,'Gekko',0)

我没有收到错误,但是当我这样写时:

data$Segment <- if (data$RankAll<4) 'Moore' else if 
                   (data$RankAll<6) 'Marvin' else if
                   (data$RankAll<8)'Branes' else if 
                   (data$RankAll<10) 'Fox' else 'Gekko'

它返回错误:

Warning messages:
 1: In if (data$RankAll < 4) "Moore" else if (data$RankAll < 6) "Marvin" else if (data$RankAll <  :
  the condition has length > 1 and only the first element will be used
2: In if (data$RankAll < 6) "Marvin" else if (data$RankAll < 8) "Branes" else if (data$RankAll <  :
  the condition has length > 1 and only the first element will be used
 3: In if (data$RankAll < 8) "Branes" else if (data$RankAll < 10) "Fox" else "Gekko" :
  the condition has length > 1 and only the first element will be used
 4: In if (data$RankAll < 10) "Fox" else "Gekko" :

条件的长度> 1,只使用第一个元素

我做错了什么?

1 个答案:

答案 0 :(得分:1)

请参阅上面评论中的SamDickson的方法,以获得与原始逻辑保持相同逻辑的方法。

用DRYer代码做同样的事情:

data$Segment <- cut(data$RankAll, breaks = c(0, 4, 6, 8, 10, 100), right = FALSE)
levels(data$Segment) <- c('Moore', 'Marvin', 'Branes', 'Fox', 'Gekko')