Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - How to pass some (but not all) further arguments with "..."

One of my in-progress functions calls grep() with value = TRUE hard-coded. I'd like to pass all of the further arguments except value to grep() through with .... The two functions below are tests I've done so far, neither of which gets the job done.

What is the best way to exclude one or more further arguments when using ... ?

Practice function 1:

f <- function(pattern, x, ...)
{
    dots <- list(...)
    if('value' %in% names(dots)) 
        dots <- dots[!grepl('value', names(dots))]
    grep(pattern, x, value = TRUE, ...)
}

XX <- c('bct', 'abc', 'fds', 'ddabcff', 'jkl')    
## test f()
f('abc', XX, value = TRUE) ## to test the error if user enters 'value' argument
# Error in grep(pattern, x, value = TRUE, ...) : 
#     formal argument "value" matched by multiple actual arguments
f('abc', XX, invert = TRUE)
# [1] "bct" "fds" "jkl"
f('ABC', XX, ignore.case = TRUE)
# [1] "abc"     "ddabcff"

Practice function 2:

h <- function(pattern, x, ...) x[grep(pattern, x, ...)]    
## test h()
h('abc', XX, value = TRUE)
# [1] NA NA
h('abc', XX, invert = TRUE)
# [1] "bct" "fds" "jkl"
h('ABC', XX, ignore.case = TRUE)
# [1] "abc"     "ddabcff"
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 combine Curry with do.call:

require(functional)
f <- function(pattern, x, ...)
{
  dots <- list(...)
  dots <- dots[!grepl('value', names(dots))]
  do.call(Curry(grep, pattern=pattern, x=x, value=TRUE), dots)
}

Curry provides the known arguments, and dots supplies everything other than "value" in ....


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...