Learn R Programming

Ecfun (version 0.2-2)

compareLengths: Compare the lengths of two objects

Description

Issue a warning or error if the lengths of two objects are not compatible.

Usage

compareLengths(x, y, 
   name.x=deparse(substitute(x), width.cutoff, nlines=1, ...), 
   name.y=deparse(substitute(y), width.cutoff, nlines=1, ...), 
   message0='', compFun=c('NROW', 'length'), 
   action=c(compatible='', incompatible='warning'), 
   length0=c('compatible', 'incompatible', 'stop'), 
   width.cutoff=20, ...)

Arguments

x, y

objects whose lengths are to be compared

name.x, name.y

names of x and y to use in a message. Default = deparse(substitute(.), width.cutoff, nlines=1).

message0

character string to be included with name.x and name.y in a message.

compFun

function to use in the comparison.

action

A character vector of length 2 giving the names of functions to call if the lengths are not equal but are either 'compatible' or 'incompatible'; '' means no action.

length0

If length(x) or length(y) = 0 (but not both), treat this case as specified by length0.

width.cutoff

width.cutoff argument to pass to deparse. This gives the maximum number of characters to use in a name in error and warning messages.

optional arguments for deparse

Value

A character vector of length 2. The first element is either 'equal', 'compatible' or 'incompatible'. The second element is the message composed.

Details

1. If nchar(name.x) = 0 = nchar(name.y), set name.x <- 'x', name.y <- 'y', and append 'in compareLengths:' to message0 for more informative messaging.

2. lenx <- do.call(compFun, list(x)); leny <- do.call(compFun, list(y))

3. if(lenx==leny)return(c('equal', ''))

4. Compatible?

5. Compose the message.

6. "action", as indicated

See Also

interpChar

Examples

Run this code
# NOT RUN {
##
## 1.  equal 
##
# }
# NOT RUN {
all.equal(compareLengths(1:3, 4:6), c("equal", ''))
# }
# NOT RUN {
##
## 2.  compatible 
##
a <- 1:2
b <- letters[1:6]
comp.ab <- compareLengths(a, b, message0='Chk:')
comp.ba <- compareLengths(b, a, message0='Chk:')
# check 
chk.ab <- c('compatible', 
            'Chk: length(b) = 6 is 3 times length(a) = 2')
# }
# NOT RUN {
all.equal(comp.ab, chk.ab) 
# }
# NOT RUN {
all.equal(comp.ba, chk.ab) 
# }
# NOT RUN {
##
## 3.  incompatible 
##
Z <- LETTERS[1:3]
comp.aZ <- compareLengths(a, Z)
# check 
chk.aZ <- c('incompatible', 
    ' length(Z) = 3 is not a multiple of length(a) = 2')
# }
# NOT RUN {
all.equal(comp.aZ, chk.aZ) 
# }
# NOT RUN {
##
## 4.  problems with name.x and name.y 
##
comp.ab2 <- compareLengths(a, b, '', '')
# check 
chk.ab2 <- c('compatible', 
             'in compareLengths: length(y) = 6 is 3 times length(x) = 2')
# }
# NOT RUN {
all.equal(comp.ab2, chk.ab2) 
# }
# NOT RUN {
##
## 5.  zeroLength 
##
zeroLen <- compareLengths(logical(0), 1) 
# check 
zeroL <- c('compatible', ' length(logical(0)) = 0')
# }
# NOT RUN {
all.equal(zeroLen, zeroL)
# }

Run the code above in your browser using DataLab