Search code examples
rargumentsvariadic-functions

Using an undefined (misspelled) argument in `paste` function - understand the result


We all know there is a collapse argument in paste() function. It refers to an optional character string to separate the results:

paste(1:5, collapse = ", ")  
[1] "1, 2, 3, 4, 5"

But, also when the collapse argument is misspelled - e.g. cpllapse - the call doesn't error, although the result is confusing:

paste(1:5, cpllapse = ", ")
[1] "1 , " "2 , " "3 , " "4 , " "5 , "

I googled the cpllapse parameter in R, but could not find anything.

Why doesn't paste() error when using a misspelled argument, and how can the result be explained? Or is there actually a cpllapse parameter in paste()?


Solution

  • paste has the ellipses ... as its first parameter. The ellipses collects all function arguments that don't match one of paste's named parameters.

    The help page says:

    ... one or more R objects, to be converted to character vectors.

    You are passing two R objects and it does not matter that one of them is a named argument, due to how the ellipses and argument matching work in R. As usual in R, input vectors are recycled to the length of the longest input vector.

    What you are doing there is basically the same as paste(1:5, rep(", ", 5), sep = " ").