简体   繁体   English

重复的else if语句的快捷方式

[英]shortcut for repetitive else if statement

I have to write repetitive else if conditions like: 如果条件如下,我必须写重复的其他内容:

  if (d_hand[1]==1){
    state=score(p_hand)-1
  } else if (d_hand[1]==2){
    state=19+score(p_hand)
  } else if (d_hand[1]==3){
    state=39+score(p_hand)
  } else if (d_hand[1]==4){
    state=59+score(p_hand)
  } else if (d_hand[1]==5){
    state=79+score(p_hand)
  } else if (d_hand[1]==6){
    state=99+score(p_hand)
  }

Do you know if it could be written more efficiently/shortly? 你知道它是否可以更快/更快地写出来吗? I thought about doing a loop of if but it would be less efficient since every statement would have to be examined. 我想过做一个if循环,但效率会降低,因为必须检查每个语句。

ifelse没有ifelse

state <- score(p_hand) + 20 * d_hand[1] - 21

Maybe a lookup table. 也许是查找表。

add <- c(-1, 19, 39, 59, 79, 99)
state <- add[which(1:6 == d_hand[1])] + score(p_hand)

You can either use switch from base, or dplyr case_when : 您可以使用从base switch ,也可以使用dplyr case_when

library(dplyr)
state <- case_when(d_hand[1]==1 ~ {score(p_hand)-1}, 
          d_hand[1]==2 ~ 19+score(p_hand), 
          d_hand[1]==3 ~ 39+score(p_hand), 
          d_hand[1]==4 ~ 59+score(p_hand),
          d_hand[1]==5 ~ 79+score(p_hand), 
          d_hand[1]==6 ~ 99+score(p_hand)
)

This logic is very close to @Martin. 这个逻辑非常接近@Martin。

state <- score(p_hand) + 20*(d_hand[1]-1) - 1

EDIT I had thought to gain some performance benefit but I had missed one point. 编辑我曾想过获得一些性能优势,但我错过了一点。 I'll share details of microbenchmark performance later. 我将在稍后分享微microbenchmark性能的细节。 But performance of @Martin is better than mine (which obvious). 但@Martin的表现比我的好(显而易见)。

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

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