我试图将所有NA传递给函数的内容更改为NULL. 我想要的不是按名称单独处理每个参数,而是捕获所有参数,过滤那些参数并将NA它们更改为 NULL。
foo <- function(a, b = NA, c = NA) {
print(a)
print(b)
print(c)
# do something to capture all args and change NAs to NULL
print(a)
print(b)
print(c)
}
# expected output
> foo(a = 1)
[1] 1
[1] NA
[1] NA
[1] 1
[1] NULL
[1] NULL
Run Code Online (Sandbox Code Playgroud)
编辑:包含一个没有默认值的参数
要访问函数的参数,请使用formals.
foo <- function(a = 1, b = NA, c = NA) {
print(a)
print(b)
print(c)
# do something to capture all args and change NAs to NULL
frm <- formals()
cat("-----------\n")
print(frm)
frm <- lapply(frm, \(x) {
if(is.na(x)) NULL else x
})
cat("-----------\n")
with(frm, {
print(a)
print(b)
print(c)
})
}
foo()
#> [1] 1
#> [1] NA
#> [1] NA
#> -----------
#> $a
#> [1] 1
#>
#> $b
#> [1] NA
#>
#> $c
#> [1] NA
#>
#> -----------
#> [1] 1
#> NULL
#> NULL
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v2.0.1)于 2022-03-28 创建
评论表明这个问题也在要求match.call。但它的返回值必须被强制列出。
check_arrays <- function(a, b, c, d) {
print(as.list(match.call()))
}
check_arrays(a = 'teststring', b = 1, c = NA, d = NA)
#> [[1]]
#> check_arrays
#>
#> $a
#> [1] "teststring"
#>
#> $b
#> [1] 1
#>
#> $c
#> [1] NA
#>
#> $d
#> [1] NA
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v2.0.1)于 2022-03-28 创建
NA下面是一个将所有参数更改为 的示例NULL,就像上面的第一个函数一样。
check_arrays <- function(a, b, c, d) {
print(a)
print(b)
print(c)
print(d)
# do something to capture all args and change NAs to NULL
# note that the first element of the list is the function
# name, remove it
args_list <- as.list(match.call())[-1]
cat("-----------\n")
print(args_list)
args_list <- lapply(args_list, \(x) {
if(is.na(x)) NULL else x
})
cat("-----------\n")
with(args_list, {
print(a)
print(b)
print(c)
print(d)
})
}
check_arrays(a = 'teststring', b = 1, c = NA, d = NA)
#> [1] "teststring"
#> [1] 1
#> [1] NA
#> [1] NA
#> -----------
#> $a
#> [1] "teststring"
#>
#> $b
#> [1] 1
#>
#> $c
#> [1] NA
#>
#> $d
#> [1] NA
#>
#> -----------
#> [1] "teststring"
#> [1] 1
#> NULL
#> NULL
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v2.0.1)于 2022-03-28 创建