[R] promoting scalar arguments to vectors in a function

Marc Schwartz marc_schwartz at me.com
Mon May 23 18:25:26 CEST 2016


On May 23, 2016, at 10:59 AM, JLucke at ria.buffalo.edu wrote:
> 
> R users: 
> 
> Suppose I have a function that takes three numeric arguments x, y,  and z, 
> any of which may be scalars or vectors.
> Suppose further that the user takes one of the arguments, say y, as a 
> vector with the other two as scalars.
> Is there an existing R function that will promote the other two arguments 
> to vectors of the same size?
> 
> I know in most cases this is not a problem as the promotion is automatic. 
> I need this for a function I am writing
> and I don't want to write any additional code to do this if I can help it.
> 
> Joe


For a general overview of R's recycling approach, see:

  https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Vector-arithmetic

and:

  https://cran.r-project.org/doc/manuals/r-release/R-intro.html#The-recycling-rule

The question is what type of error checking you want to embed in your function, if the lengths of each argument are not the same and that would be a problem. Do you want to presume that a user will pass arguments that fit your a priori expectation, or protect against the possibility that they do not?

What would you do if y is a vector of length 6, x is a vector of length 1 and z is a vector of length 8?

R's default rules would replicate 'x' 8 times (e.g. rep(x, 8)), while extending 'y' by 2 (e.g. y <- y[c(1:6, 1:2)]), so that both have length(z).

You can use something along the lines of:

Max.Len <- max(length(x), length(y), length(z))
x <- rep(x, length.out = Max.Len)
y <- rep(y, length.out = Max.Len)
z <- rep(z, length.out = Max.Len)

which will recycle each as may be needed so that they have a common length.

Only you will know, given your function, if that might result in problems in whatever result your function is intended to generate.

Regards,

Marc Schwartz



More information about the R-help mailing list