agstudy agstudy - 1 year ago 84
R Question

Partial matching of function argument

I know that for a list, partial matching is done when indexing using the basic operators

. For example:

ll <- list(yy=1)
[1] 1

But I am still an R newbie and this is new for me, partial matching of function arguments:

h <- function(xx=2)xx
[1] 2

I want to understand how this works. What is the mechanism behind it? Does this have any side effects? I want understand how can someone test if the xx argument was given?

Edit after Andrie comment:

Internally R uses
algorithm to match argument, here an example how this works:

pmatch("me", c("mean", "median", "mode")) # error multiple partial matches
[1] NA
> pmatch("mo", c("mean", "median", "mode")) # mo match mode match here
[1] 3

But why R has such feature? What is the basic idea behind of
partial unique

Answer Source

Partial matching exists to save you typing long argument names. The danger with it is that functions may gain additional arguments later on which conflict with your partial match. This means that it is only suitable for interactive use – if you are writing code that will stick around for a long time (to go in a package, for example) then you should always write the full argument name. The other problem is that by abbreviating an argument name, you can make your code less readable.

Two common good uses are:

  1. len instead of length.out with the seq (or function.

  2. all instead of all.names with the ls function.

Compare:, 1, len = 11), 1, length.out = 11)

ls(all = TRUE)
ls(all.names = TRUE)

In both of these cases, the code is just about as easy to read with the shortened argument names, and the functions are old and stable enough that another argument with a conflicting name is unlikely to be added.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download