Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
避免R中的If-Then-Else结构_R_If Statement - Fatal编程技术网

避免R中的If-Then-Else结构

避免R中的If-Then-Else结构,r,if-statement,R,If Statement,我面临的任务是从矩阵列表中返回一些行。要返回的行可以作为数字或“第一行”和“最后一行”输入。我将其编码如下: showrow <- function(row) { if (class(row) == "numeric") { getrow <- function(d) { d[row,] } return(getrow) } else { if (row =="first") { getrow <- functio

我面临的任务是从矩阵列表中返回一些行。要返回的行可以作为数字或“第一行”和“最后一行”输入。我将其编码如下:

showrow <- function(row) {
  if (class(row) == "numeric") {
    getrow <- function(d) {
      d[row,]
    }
    return(getrow)
  } else {
    if (row =="first") {
      getrow <- function(d) {
        head(d, 1)
      }
      return(getrow)
    } else {
      if (row == "last") {
        getrow <- function(d) {
          tail(d, 1)
        }
        return(getrow)
      } else {
        stop("invalid position")
      }
    }
  }
}
showrow这里有一种方法:

showrow <- function(row) {
  if (class(row) == "numeric") return(function(d) d[row,])
  f <- list(first=head,last=tail)[[row]]
  if (is.null(f)) stop("invalid position")
  function(d) f(d,1)
}

showrow这里有一个
开关
解决方案

showrow <- function(row) {
  switch(class(row),
         numeric = function(d) {
           d[row,]
         },
         character = switch(row,
                            first = function(d){
                              head(d,1)
                            },
                            last = function(d){
                              tail(d,1)
                            },
                            {stop("Invalid position")}),
        {stop("Invalid position")}
  )
}

showrow如果将界面更改为:

如果您给我的不是数字,请显示最后一行,否则显示该行:

因为
1
可以正常工作,所以“first”不需要特殊标记。然后你可以做这样的事情。显然,
showrow(“first”)(mx)
仍将返回最后一行,这可能会让人困惑。实际上,最好的办法是:

如果我指定了某一行,则显示该行;如果我没有指定,则显示最后一行

这更容易实现

showrow <- function(row) {
  switch(class(row),
         numeric = function(d) {
           d[row,]
         },
         character = switch(row,
                            first = function(d){
                              head(d,1)
                            },
                            last = function(d){
                              tail(d,1)
                            },
                            {stop("Invalid position")}),
        {stop("Invalid position")}
  )
}
showrow <- function(row) {
  if(!is.numeric(row)) return(function(x) tail(x, 1L))
  function(x) tryCatch(x[row, ], error=function(e) NA)
}
showrow("last")(a)   # Last row
showrow(4)(a)        # 4th row (also last in this case)
showrow(2:3)(a)      # 2nd and 3rd
showrow(20)(a)       # Returns NA