How to use the switch statement in R functions?

前端 未结 4 1044
傲寒
傲寒 2020-11-29 19:32

I would like to use for my function in R the statement switch() to trigger different computation according to the value of the function\'s argument.

Fo

4条回答
  •  无人及你
    2020-11-29 20:15

    This is a more general answer to the missing "Select cond1, stmt1, ... else stmtelse" connstruction in R. It's a bit gassy, but it works an resembles the switch statement present in C

    while (TRUE) {
      if (is.na(val)) {
        val <- "NULL"
        break
      }
      if (inherits(val, "POSIXct") || inherits(val, "POSIXt")) {
        val <- paste0("#",  format(val, "%Y-%m-%d %H:%M:%S"), "#")
        break
      }
      if (inherits(val, "Date")) {
        val <- paste0("#",  format(val, "%Y-%m-%d"), "#")
        break
      }
      if (is.numeric(val)) break
      val <- paste0("'", gsub("'", "''", val), "'")
      break
    }
    

提交回复
热议问题