简体   繁体   English

R中Ifelse语句的用法

[英]Ifelse statement usage in R

I have a data frame "var" and I need to get a vector output that satisfies the following conditions. 我有一个数据帧“ var”,我需要获得满足以下条件的向量输出。

Basically, what I am trying to execute is the following: if the value of psqi_2_sleepstart1 is less than 15, comp21score needs to be assigned the value 0; 基本上,我要执行的操作如下:如果psqi_2_sleepstart1的值小于15,则需要为comp21score分配值0; between 16 and 30, comp21score needs to be assigned the value 1; 在16到30之间,需要为comp21score分配值1; between 31 and 60, comp21score needs to be assigned the value 2 and over 60 comp21score should take the value of 3. For example, if the data frame had values for psqi_2_sleepstart1 as 16, 40, 6 and 10; 在31到60之间,需要为comp21score分配值2,超过60的comp21score应当取值为3。例如,如果数据帧的psqi_2_sleepstart1值为16、40、6和10; I want the output to be 1, 2, 0, 1. I was using the ifelse statement, but I got the error that argument "yes" is missing, with no default. 我希望输出为1、2、0、1。我正在使用ifelse语句,但是却收到错误消息,缺少参数“ yes”,没有默认值。

Here is my attempt: 这是我的尝试:

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)

Does anyone have suggestions on what I might be able to use instead or how to avoid this error? 是否有人对我可能会使用的建议或如何避免此错误的建议?

Thanks! 谢谢!

Just for kicks - here is a case_when dplyr example (as mentioned in the comments): 只为踢球-这是一个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
.....

Use this layout instead: 请改用以下布局:

x <- 2

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM