在 R 函数中使用可选参数
Using optional arguments in R function
我想在下面的函数中使用可选参数 logbase = NULL
。但是无法找出最佳做法。请任何提示。
fn1 <- function(x, logbase = NULL){
logbase <- ifelse(test = is.null(logbase) | 10, yes = 10, no = logbase)
out <- log(x = x, base = logbase)
return(out)
}
fn1(x = 10, logbase = NULL)
1
答案错误
fn1(x = 10, logbase = 2)
1
答案错误
fn1(x = 10, logbase = exp(1))
1
这是一个变体:
fn1 <- function(x, logbase = NULL){
if(is.null(logbase)||logbase==10){
logbase=10
#logbase <- ifelse(test = is.null(logbase) | 10, yes = 10, no = logbase)
out <- log(x = x, base = logbase)
return(out)
}
else{
log(x = x, base = logbase)#?exp(logbase)
}
}
测试:
fn1(x = 10, logbase = 2)
[1] 3.321928
我的建议
我认为 | 10
部分导致了问题,因为当 logbase
为 10 时,无论测试评估为 TRUE
还是 FALSE
,你都会得到相同的结果,你可以将其删除.我知道你在评论中说过这没有按预期工作,但对我来说似乎是这样 - 如果仍然不适合你,请随时发表评论。
fn1 <- function(x, logbase = NULL){
logbase <- ifelse(test = is.null(logbase), yes = 10, no = logbase)
out <- log(x = x, base = logbase)
return(out)
}
fn1(x = 10, logbase = NULL) # 1
fn1(x = 10, logbase = 2) # 3.321928
fn1(x = 10, logbase = exp(1)) # 2.302585
你的代码有什么问题
问题是 | 10
的任何值都将始终计算为 TRUE
。这是因为 |
运算符会将两边的参数都转换为 logical
,因此 is.null(2) | 10
等价于 as.logical(is.null(2)) | as.logical(10)
,其计算结果为 F | T
,即T
.
需要说明的是,| 10
与 logbase 无关。您正在寻找的大概是 | logbase == 10
。这很好,除非 logbase 是 NULL
,你 运行 会遇到问题,因为 NULL == 10
的计算结果不是 T
或 F
(它是 logical(0)
).
您可以通过使用 ||
而不是 |
来解决这个问题,如果 is.null(logbase)
是 FALSE
,它只会评估 logbase == 10
,因为如果 FALSE
的前半部分=30=] 是 TRUE
,那么它只是 returns TRUE
而不计算后半部分。
我想在下面的函数中使用可选参数 logbase = NULL
。但是无法找出最佳做法。请任何提示。
fn1 <- function(x, logbase = NULL){
logbase <- ifelse(test = is.null(logbase) | 10, yes = 10, no = logbase)
out <- log(x = x, base = logbase)
return(out)
}
fn1(x = 10, logbase = NULL)
1
答案错误
fn1(x = 10, logbase = 2)
1
答案错误
fn1(x = 10, logbase = exp(1))
1
这是一个变体:
fn1 <- function(x, logbase = NULL){
if(is.null(logbase)||logbase==10){
logbase=10
#logbase <- ifelse(test = is.null(logbase) | 10, yes = 10, no = logbase)
out <- log(x = x, base = logbase)
return(out)
}
else{
log(x = x, base = logbase)#?exp(logbase)
}
}
测试:
fn1(x = 10, logbase = 2)
[1] 3.321928
我的建议
我认为 | 10
部分导致了问题,因为当 logbase
为 10 时,无论测试评估为 TRUE
还是 FALSE
,你都会得到相同的结果,你可以将其删除.我知道你在评论中说过这没有按预期工作,但对我来说似乎是这样 - 如果仍然不适合你,请随时发表评论。
fn1 <- function(x, logbase = NULL){
logbase <- ifelse(test = is.null(logbase), yes = 10, no = logbase)
out <- log(x = x, base = logbase)
return(out)
}
fn1(x = 10, logbase = NULL) # 1
fn1(x = 10, logbase = 2) # 3.321928
fn1(x = 10, logbase = exp(1)) # 2.302585
你的代码有什么问题
问题是 | 10
的任何值都将始终计算为 TRUE
。这是因为 |
运算符会将两边的参数都转换为 logical
,因此 is.null(2) | 10
等价于 as.logical(is.null(2)) | as.logical(10)
,其计算结果为 F | T
,即T
.
需要说明的是,| 10
与 logbase 无关。您正在寻找的大概是 | logbase == 10
。这很好,除非 logbase 是 NULL
,你 运行 会遇到问题,因为 NULL == 10
的计算结果不是 T
或 F
(它是 logical(0)
).
您可以通过使用 ||
而不是 |
来解决这个问题,如果 is.null(logbase)
是 FALSE
,它只会评估 logbase == 10
,因为如果 FALSE
的前半部分=30=] 是 TRUE
,那么它只是 returns TRUE
而不计算后半部分。