[英]Use lapply with keyword arguments
So if I am not missing something big, the way lapply/sapply/etc.所以如果我没有遗漏一些大的东西,那么 lapply/sapply/etc. works is by using the iterable element in the list as first argument, therefore forcing you to use it as positional argument of the function ( FUN
).工作是使用列表中的可迭代元素作为第一个参数,因此强制您将其用作函数的位置参数( FUN
)。
So a normal use case would be所以一个正常的用例是
foo <- function(a = NULL, b = NULL, c = NULL) {
print(glue::glue("a: {a}"))
print(glue::glue("b: {b}"))
print(glue::glue("c: {c}"))
}
lapply(letters[1:3], foo)
#> a: a
#>
#>
#> a: b
#>
#>
#> a: c
#> [[1]]
#>
#>
#> [[2]]
#>
#>
#> [[3]]
However, if I want to iterate through the list as b instead, I am forced to set a value to a.但是,如果我想以 b 的形式遍历列表,则必须将值设置为 a。 Like this.像这样。
lapply(letters[1:3], foo, a = NULL)
#>
#> b: a
#>
#>
#> b: b
#>
#>
#> b: c
#> [[1]]
#>
#>
#> [[2]]
#>
#>
#> [[3]]
lapply(letters[1:3], foo, a = NULL,b = NULL )
#>
#>
#> c: a
#>
#>
#> c: b
#>
#>
#> c: c
#> [[1]]
#> c: a
#>
#> [[2]]
#> c: b
#>
#> [[3]]
#> c: c
I know I can set it to the default value but I would like to know if there is a way to use the iterated elements as keyword argument instead of positional argument.我知道我可以将它设置为默认值,但我想知道是否有办法使用迭代元素作为关键字参数而不是位置参数。
It would also be handy for the purrr::map
family but as far as I looked such option is not available either.它对于purrr::map
系列也很方便,但purrr::map
来,这样的选项也不可用。
Created on 2019-12-24 by the reprex package (v0.3.0)由reprex 包(v0.3.0) 于 2019 年 12 月 24 日创建
Simply define a new anonymous function to associate the argument with the name, eg只需定义一个新的匿名函数来将参数与名称相关联,例如
lapply(letters[1:3], function(x) foo(b = x))
If you're using purrr
, there's a bit less typing, but conceptually you're doing the same thing:如果您使用purrr
,则打字会少一些,但从概念上讲,您正在做同样的事情:
purrr::map(letters[1:3], ~ foo(b = .))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.