在一些R函数的主体中,例如lm我看到对match.call函数的调用.正如帮助页面所说,在函数内部使用时会match.call返回一个调用,其中指定了参数名称; 这对于将大量参数传递给另一个函数应该是有用的.
例如,在lm函数中我们看到对函数的调用model.frame
function (formula, data, subset, weights, na.action, method = "qr",
model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE,
contrasts = NULL, offset, ...)
{
cl <- match.call()
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "subset", "weights", "na.action",
"offset"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf[[1L]] <- quote(stats::model.frame)
mf <- eval(mf, parent.frame())
...
Run Code Online (Sandbox Code Playgroud)
为什么这比直接调用model.frame指定参数名称更有用呢?
function (formula, …Run Code Online (Sandbox Code Playgroud) 我正在尝试修改自定义函数中的点(...).这是我的plot2函数的简化示例,它在屏幕上显示一个图type="p"(默认值)并保存一个svg type="l".当其中一个...绘图选项已在函数中时,问题就会浮现.在此示例中,"type"由多个实际参数匹配.
plot2 <-function(...){
plot(...) #visible on screen
svg("c:/temp/out.svg") #saved to file
plot(...,type="l")
dev.off()
}
#This works
plot2(1:10)
#This does not work because type is redefined
plot2(1:10, type="o")
Run Code Online (Sandbox Code Playgroud)
我试图将点list放在函数内部并修改它,但plot不接受列表作为输入.
#Does not work
plot2 <-function(...){
plot(...)
dots <<-list(...)
print(dots)
if("type" %in% names(dots)) dots$type="l"
print(dots)
svg("c:/temp/out.svg")
plot(dots)
dev.off()
}
plot2(1:10, type="o")
Error in xy.coords(x, y, xlabel, ylabel, log) :
'x' is a list, but does not have components 'x' …Run Code Online (Sandbox Code Playgroud) 如何获取包含传递给函数的点 - 点参数名称的字符向量,例如:
test<-function(x,y,...)
{
varnames=deparseName(substitute(list(...)))
# deparseName does not exist, this is what I want !
# so that I could *for example* call:
for(elt in varnames)
{print(varnames);}
}
v1=11
v2=10
test(12,12,v1,v2)
## would print
#v1
#v2
Run Code Online (Sandbox Code Playgroud)