避免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