How to pass some (but not all) additional arguments using "..."

One of my built-in functions calls grep()with a value = TRUEhard-coded one. I would like to convey all the additional arguments , except value , grep()through .... Below are the two tests below that I have done so far, none of which are doing their job.

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

Practical 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"

Practical 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"
+4
source share
2 answers

- , - , , .

f <- function(pattern, x, value = "hahaThisGetsIgnored", ...){
   grep(pattern, x, value = TRUE, ...)
}

@MatthewLundberg, , Curry,

f <- function(pattern, x, ...){
  dots <- list(...)
  # Remove value from the dots list if it is there
  dots$value <- NULL
  args <- c(list(pattern = pattern, x = x, value = TRUE), dots)
  do.call(grep, args)
}
+2

Curry 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 , dots , "", ....

+4

Source: https://habr.com/ru/post/1541946/


All Articles