我有一个矢量 arguments
,其中一些值为 NA
.我想将这些参数按顺序传递给这样的函数:
myFunction(argument = ifelse(!is.na(arguments[i]),
arguments[i], NULL))
以便它将采用 arguments[i]
中的值只要不是 NA
,并采用默认 NULL
除此以外。但这会产生错误。如果它有任何区别,则有问题的函数是
match_on()
,来自 optmatch
包裹。有问题的论点是 caliper
,因为我只想在一个可用的情况下提供一个卡尺(即当卡尺向量中的值不是 NA
时)。错误信息是这样的:Error in ans[!test & ok] <- rep(no, length.out = length(ans))[!test & :
replacement has length zero
In addition: Warning message:
In rep(no, length.out = length(ans)) :'x' is NULL so the result will be NULL
最佳答案
您可以使用 ?switch()
而不是 ifelse
——
myFunction(argument = switch(is.na(arguments[i]) + 1, arguments[i], NULL))
这是
switch
的帮助文档——switch(EXPR, ...)
Arguments
EXPR an expression evaluating to a number or a character string.
... the list of alternatives. If it is intended that EXPR has a character-string value these will be named, perhaps except for one alternative to be used as a ‘default’ value.
Details
switch works in two distinct ways depending whether the first argument evaluates to a character string or a number.
If the value of EXPR is not a character string it is coerced to integer. If the integer is between 1 and nargs()-1 then the corresponding element of ... is evaluated and the result returned: thus if the first argument is 3 then the fourth argument is evaluated and returned
基本上,当参数是
NA
然后 EXPR
计算结果为 2 返回 NULL
如果不是 NA
然后 EXPR
计算结果为 1 并返回 arguments[i]
.
关于r - 如何在 R 中将 NULL 作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53462180/