带有多个条件语句的虚拟代码,用于返回R中的多个选项

时间:2017-06-13 18:35:19

标签: r

我需要通过创建执行以下操作的列来将我的数据编码为三组:

0 =如果jobentrydat_alltechs $ Jobcode + =“101545”,“101318”,“100897”,“100895”,“100891”,“100885”,“100884”,“100880”,“100875”,“100873” AND jobentrydat_alltechs $ Term.Date + = NA

1 =如果jobentrydat_alltechs $ Jobcode =“101545”,“101318”,“100897”,“100895”,“100891”,“100885”,“100884”,“100880”,“100875”,“100873”和jobentrydat_alltechs $ Term.Date!= NA

2 =其他一切

目前已尝试

> jobentrydat_alltechs$typeofterm <- if(jobentrydat_alltechs$Jobcode ==
> c("101545", "101318", "100897", "100895", "100891", "100885",
> "100884", "100880", "100875", "100873") &
>           jobentrydat_alltechs$Term.Date == is.na(jobentrydat_alltechs$Term.Date)) {
>             print("0")
>           } else if (jobentrydat_alltechs$Jobcode == c("101545", "101318", "100897", "100895", "100891", "100885", "100884", "100880",
> "100875", "100873") &
>             jobentrydat_alltechs$Term.Date != is.na(jobentrydat_alltechs$Term.Date)) {
>               print("1")
>             } else {
>               print("2")
>             }

我也尝试过使用ifelse,但我并不熟悉ifelse。我确定我错过了一些明显的东西,但这周二感觉就像第二个星期一。

警告讯息:

1: In is.na(e1) | is.na(e2) :
  longer object length is not a multiple of shorter object length
2: In `==.default`(jobentrydat_alltechs$Jobcode, c("101545", "101318",  :
  longer object length is not a multiple of shorter object length
3: In if (jobentrydat_alltechs$Jobcode == c("101545", "101318", "100897",  :
  the condition has length > 1 and only the first element will be used
4: In is.na(e1) | is.na(e2) :
  longer object length is not a multiple of shorter object length
5: In `==.default`(jobentrydat_alltechs$Jobcode, c("101545", "101318",  :
  longer object length is not a multiple of shorter object length
6: In if (jobentrydat_alltechs$Jobcode == c("101545", "101318", "100897",  :
  the condition has length > 1 and only the first element will be used

2 个答案:

答案 0 :(得分:0)

conditional.return <- function (bool1, bool2) {
    if (bool1 & bool2) return (0)
    else if (bool1 & !(bool2)) return (1)
    else return (2)
}

cond1 <- jobentrydat_alltechs$Jobcode %in% c("101545", "101318", "100897", "100895", "100891", "100885", "100884", "100880", "100875", "100873")
cond2 <- is.na(jobentrydat_alltechs$Term.Date)

jobentrydat_alltechs$typeofterm <- mapply(conditional.return, cond1, cond2)

答案 1 :(得分:0)

这应该有效:

jobentrydat_alltechs$typeofterm <- ifelse((jobentrydat_alltechs$Jobcode %in% 
    c("101545","101318", "100897", "100895", "100891", "100885","100884", 
      "100880", "100875", "100873") & is.na(jobentrydat_alltechs$Term.Date)), "0",  
    ifelse((jobentrydat_alltechs$Jobcode %in% c("101545", "101318", "100897",
           "100895", "100891", "100885", "100884", "100880","100875", 
           "100873") & != is.na(jobentrydat_alltechs$Term.Date)), "1", "2")) 

唯一的区别是我将==更改为%in%,然后使用了2个ifelse语句。