R语言有一个很好的功能,用于定义可以采用可变数量参数的函数.例如,该函数data.frame接受任意数量的参数,并且每个参数都成为结果数据表中列的数据.用法示例:
> data.frame(letters=c("a", "b", "c"), numbers=c(1,2,3), notes=c("do", "re", "mi"))
letters numbers notes
1 a 1 do
2 b 2 re
3 c 3 mi
Run Code Online (Sandbox Code Playgroud)
函数的签名包括省略号,如下所示:
function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,
stringsAsFactors = default.stringsAsFactors())
{
[FUNCTION DEFINITION HERE]
}
Run Code Online (Sandbox Code Playgroud)
我想编写一个类似的函数,获取多个值并将它们合并为一个返回值(以及进行一些其他处理).为了做到这一点,我需要弄清楚如何...从函数中的函数参数"解包" .我不知道该怎么做.功能定义中的相关行data.frame是object <- as.list(substitute(list(...)))[-1L],我无法理解.
那么如何将省略号从函数的签名转换为例如列表呢?
更具体地说,我如何写get_list_from_ellipsis下面的代码?
my_ellipsis_function(...) {
input_list <- get_list_from_ellipsis(...)
output_list <- lapply(X=input_list, FUN=do_something_interesting)
return(output_list)
}
my_ellipsis_function(a=1:10,b=11:20,c=21:30)
Run Code Online (Sandbox Code Playgroud)
似乎有两种可能的方法来做到这一点.他们是as.list(substitute(list(...)))[-1L]和list(...).但是,这两者并没有完全相同.(有关差异,请参阅答案中的示例.)任何人都可以告诉我它们之间的实际区别是什么,我应该使用哪一个?
是否可以从...中删除元素并将...传递给其他函数?我的前两次尝试失败了:
parent = function(...)
{
a = list(...)
str(a)
a$toRemove = NULL
str(a)
# attempt 1
child(a)
# attempt 2
child( ... = a )
}
child = function(...)
{
a = list( ... )
str(a)
}
parent( a = 1 , toRemove = 2 )
Run Code Online (Sandbox Code Playgroud)
编辑
抱歉混乱.我修了孩子().目的是让孩子列出......的内容
Edit2
这里有一个更真实的例子(但仍然相当简单,所以我们可以就此进行有用的对话).父通过递归调用.父需要知道递归调用的深度.父母以外的来电者不应该知道"深度",也不应该在调用parent()时设置它.Parent调用其他函数,在本例中为child().孩子需要值...显然,孩子不需要"深度",因为父母为自己的使用生成了它.
parent = function( ... )
{
depth = list(...)$depth
if ( is.null( depth ) )
{
depth = 1
}
print( depth )
# parent needs value of depth to …Run Code Online (Sandbox Code Playgroud) 我最近在R中看到了一个有人用作.参数的函数.我似乎无法找到任何关于此的文档(除了使用省略号或"点 - 点").有人可以指向我的文档方向或提供使用示例吗?
hello.world <- function(.) "Hello World"
# function(.) is what I'm asking about.
Run Code Online (Sandbox Code Playgroud)