[R] argument rationalization

Robin Hankin rksh at soc.soton.ac.uk
Mon Nov 15 10:25:03 CET 2004



  > I think you should implement recycling, ideally at C level.
  > But you could have
  >
  > f <- function(x, y, z)
  > {
  >    n <- max(length(x), length(y), length(z))
  >    .C("something", as.double(rep(x, len=n)), as.double(rep(y, len=n)),
  >       as.double(rep(z, len=n)), as.integer(n), ans)$ans
  > }


yes!  this works exactly as desired.  Thank you.  Another thing
that is incidentally satisfied by this scheme is to preserve
attributes such as dimensions and dimnames.  It seems to me to make
sense to use the attributes of the longest argument, and then set them
after the call


to wit

f <- function(x, y, z)
{
    lens <- c(length(x), length(y), length(z))
    all.attributes <- list(attributes(x),attributes(y),attributes(z))
    n <- max(lens)
    attributes.desired <- all.attributes[[which.max(lens)]]

    .C("something", as.double(rep(x, len=n)), as.double(rep(y, len=n)),
       as.double(rep(z, len=n)), as.integer(n), ans)$ans

    attributes(ans) <- attributes.desired
    return(ans)
}



Is this good practice?

best wishes

rksh




>  >
>  > On Mon, 15 Nov 2004, Robin Hankin wrote:
>  >
>
>  Hi
>
>  I am writing a bunch of functions that take two, three or four
>  arguments.  These functions operate on vectors of the same length; but
>  I want the function
>  to behave sensibly if one or more arguments are scalars


-- 
Robin Hankin
Uncertainty Analyst
Southampton Oceanography Centre
SO14 3ZH
tel +44(0)23-8059-7743
initialDOTsurname at soc.soton.ac.uk (edit in obvious way; spam precaution)




More information about the R-help mailing list