Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

how to pass the "..." parameters in the parent function to its two children functions in r

I am trying to pass a set of parameters into a function. This function has two sub functions that take part of the above set of parameters.

In the following "SIMPLIFIED" example f_combined is a function that takes ... I would like to make the following function call such that xx is passed to f_sqr and yy is passed to f_plus:

f_combined(xx = 2, yy = 2)

but it would give me an error:

Error in f_sqr(...) : unused argument (yy = 2) 

any suggustions?

f_sqr <- function(xx =1){
  xx ^ 2
}

f_plus <- function(yy =1){
  yy + 1
}

f_combined <- function(...){
  f_sqr(...) + f_plus(...)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can either access ... as a named pairwise list or access it by order ..n

f_sqr <- function(xx =1){xx ^ 2}
f_plus <- function(yy =1){yy + 1}

f_combined <- function(...){
  print(f_sqr(list(...)$xx))
  print(f_plus(list(...)$yy))
  print(f_sqr(..1))
  print(f_plus(..2))
}
f_combined( yy = 1, xx = 10)

[1] 100 (element with name xx of the list ...)
[1] 2 (element with name yy of the list ...)
[1] 1 (the first argument in the list ...)
[1] 11 (the second argument in the list ...)

Output of ?"..."

10.4 The ‘...’ argument

Another frequent requirement is to allow one function to pass on argument settings to another. For example many graphics functions use the function par() and functions like plot() allow the user to pass on graphical parameters to par() to control the graphical output. (See The par() function, for more details on the par() function.) This can be done by including an extra argument, literally ‘...’, of the function, which may then be passed on. An outline example is given below.

 fun1 <- function(data, data.frame, graph=TRUE, limit=20, ...) {
   [omitted statements]
   if (graph)
     par(pch="*", ...)
   [more omissions]
 } 

Less frequently, a function will need to refer to components of ‘...’. The expression list(...) evaluates all such arguments and returns them in a named list, while ..1, ..2, etc. evaluate them one at a time, with ‘..n’ returning the n'th unmatched argument.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...