2

Say I have the following function in R:

tst <- function(x,y){
  foo <- match.call()
  print(foo)
}

tst(4,5)

This gives tst(x = 4, y = 5). Awesome. Now, I want to add an argument.

tst <- function(x,y){
  foo <- match.call()
  foo[[length(foo)+1]] <- 6
  print(foo)
}

tst(4,5)

This prints tst(x = 4, y = 5, 6), which is great. However, I need to add an argument name so that the function knows what to do with it. For example, I want it to be tst(x = 4, y = 5, z = 6). I tried simply foo[[length(foo)+1]] <- "z = 6", but that clearly doesn't work. I've also toyed with parse and eval without success. Any suggestions?

Dan
  • 11,370
  • 4
  • 43
  • 68
  • Why do you need a `call` output? How are you going to use it? Wouldn't it better to get a list back in the first place? – David Arenburg Jul 05 '17 at 13:12
  • It stems from [this](https://stackoverflow.com/questions/44912496/geom-smooth-with-facet-grid-and-different-fitting-functions/44913300#44913300) question. I want to modify the answer to include `nls`. Unlike `lm` and `loess` in the given answer, `nls` expects additional arguments, like `start`. So, in the `mysmooth` function I'd like to add these arguments. – Dan Jul 05 '17 at 13:15

1 Answers1

3

You can actually treat the call like a list and give it a named argument:

> tst =
function(x,y){
 foo = match.call()
 foo[["this"]] ="that"
 print(foo)
}
> tst(x=2,y=3)
tst(x = 2, y = 3, this = "that")
Spacedman
  • 92,590
  • 12
  • 140
  • 224