Created
          November 16, 2010 15:47 
        
      - 
      
- 
        Save mja/701955 to your computer and use it in GitHub Desktop. 
    Using the ... arguments programmatically with do.call
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | do.call('+', list(1, 2)) | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | f <- function(...) { | |
| arguments <- list(...) # turn them into a list | |
| for(arg in arguments ) { # loop through them | |
| # process each argument | |
| } | |
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # Use the ... to make a function that can process an arbitrary number of objects | |
| f1 <- function(...) { | |
| arguments <- list(...) # turn them into a list | |
| collection <- new.env() # store up calculations on each argument | |
| counter <- # arbitrary names | |
| for(arg in arguments ) { # loop through them | |
| # do some processing here | |
| results <- some.function.of(arg) | |
| # save the result | |
| assign(as.character(counter), result, envir=collection) | |
| counter <- counter + 1 | |
| } | |
| # now here is the magic... | |
| # f2 is also a function with the form `function(...) {}` | |
| # ________/ | |
| # / | |
| do.call(f2, as.list(collection)) | |
| # \________/ | |
| # \ | |
| # \________________________---- | |
| # / | \ | |
| # which is like we wrote `f2(result0, result1, result2, ...)` | |
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | > paste | |
| function (..., sep = " ", collapse = NULL) | |
| .Internal(paste(list(...), sep, collapse)) | |
| <environment: namespace:base> | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Thanks @mja!