[R] function to compare lengths of objects?

Duncan Murdoch murdoch.duncan at gmail.com
Mon May 5 10:55:07 CEST 2014


On 05/05/2014, 1:02 AM, Spencer Graves wrote:
>         Is there a standard function to generate messages like "longer
> object length is not a multiple of shorter object length" but providing
> more information like the names of the objects?

No, not really.

At the C level objects don't really have names.  The same object may be 
linked to several different names, or none at all.  Most messages like 
the length warning are generated there, so they don't include name 
information.

At the R level you can use substitute() to find the expression that was 
used to supply a function argument, so you can do a little better.  For 
example, I would write a simpler version of your compareLengths function 
something like this:

compareLengths <- function(x, y, name.x = deparse(substitute(x)),
                                  name.y = deparse(substitute(y))) {
   if (length(x) == length(y))
     return( c("equal", paste("objects", dQuote(name.x), "and", 
dQuote(name.y), "are the same length."))
   else ...

}

Then a function could call it like this:

f <- function(a, b) {
   cmp1 <- compareLengths(a, b)  # Message talks about  "a" and "b"
   cmp2 <- compareLengths(a, b, deparse(substitute(a)),
              deparse(substitute(b))) # Message talks about names
                                      # in call to f
   ...
}

Duncan Murdoch

>
>
>         For example, "a/b" issues, "Warning message:  In a/b : longer
> object length is not a multiple of shorter object length" if the length
> of one is not a multiple of the other.  I want a utility to produce
> messages that include the lengths of "a" and "b" and other information.
>
>
>         If you were to write such a function, what would you include in
> it?  Arguments?  Values?  Options?
>
>
>         I started creating "compareLengths.Rd" with
> \usage{compareLengths(x, y, name.x=NULL, name.y=NULL, Source='',
> compFun=c('length', 'NROW'), action=c(comparable='',
> incomparable='warning'), maxChar=20, ...)} and \value{A character vector
> of length 2.  The first element is either 'equal', 'compatible' or
> 'incompatible'.  The second element is the message composed for the
> desired "action".
>
>
>         Thanks,
>         Spencer Graves
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list