R中的Ifelse语句用法

时间:2018-06-06 16:29:42

标签: r if-statement nested

我有一个数据框“var”,我需要得到一个满足以下条件的矢量输出。

基本上,我想要执行的是:如果psqi_2_sleepstart1的值小于15,则需要为comp21score分配值0;在16到30之间,comp21score需要赋值1;在31到60之间,comp21score需要赋值为2,而60以上comp21score应该取3的值。例如,如果数据框的psqi_2_sleepstart1的值为16,40,6和10;我希望输出为1,2,0,1。我使用的是ifelse语句,但是我得到的错误是缺少参数“yes”,没有默认值。

这是我的尝试:

for (i in 1: nrow(var)) {
ifelse (psqi_2_sleepstart1 <= 15) 
comp21score [i] <- 0
ifelse (psqi_2_sleepstart1 > 15 & psqi_2_sleepstart1 <= 30)
comp21score [i] <- 1
ifelse (psqi_2_sleepstart1 > 30 & psqi_2_sleepstart1 <= 60)
comp21score [i] <- 2
ifelse (psqi_2_sleepstart1 > 60)
comp21score [i] <- 3 
}
print (comp21score)

有没有人对我可以使用的内容或如何避免此错误提出建议?

谢谢!

2 个答案:

答案 0 :(得分:2)

只是为了踢 - 这是一个case_when dplyr示例(如评论中所述):

DF1 <- data.frame("score"= 0:20)

DF1 <- DF1 %>% mutate(value = case_when(
 score < 5 ~ 1,
 score >= 5| score < 10 ~ 2,
 score >= 10 ~ 3
 )
)

> DF1
    score value
1      0     1
2      1     1
3      2     1
.....

答案 1 :(得分:0)

请改用此布局:

x <- 2

if (x==0) {
  y <- log
} else if (x == 1) {
  y <- identity
} else if (x == 2) {
  y <- function(x) x^2
}