r - 如何在 R 中将 NULL 作为参数传递?

标签 r null

我有一个矢量 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/

相关文章:

r - dplyr:评估错误:使用 gamlss 找不到对象 '.',但使用 lm、gam、glm 方法都很好

r - 如何在r中转换数据框的许多列

c - 我正确使用这些指针吗?我正在分配一些东西,但之后它立即为空

actionscript-3 - AS 3.0引用问题

javascript - 是否可以在空值的原型(prototype)中添加方法?

用因子替换范围内的数字

r - 对每个唯一组合 r 的列内的行求和

mysql - 使用 MySQL 或 r,或两者都使用?

c++ - 检查 C++ 数组是否为 Null

java - 将操作系统从 linux 更改为 windows 时的 InputStream 空指针