| length {base} | R Documentation |
Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.
length(x) length(x) <- value xlength(x) xlength(x) <- value
x |
an R object. For replacement, a vector or factor. |
value |
a non-negative integer or double (which will be rounded down). |
length and xlength differ only in the way they handle
the long vectors introduced for 64-bit builds in R 2.16.0.
All are generic: you can write methods to handle specific
classes of objects, see InternalMethods. length<- has a
"factor" method. The xlength versions will first try a
method for xlength then one of length.
The replacement form can be used to reset the length of a vector. If
a vector is shortened, extra values are discarded and when a vector is
lengthened, it is padded out to its new length with NAs
(nul for raw vectors).
All are primitive functions.
The default method for length currently returns an
integer of length 1. Since this may change in the
future and may differ for other methods, programmers should not rely
on it. It gives an error for long vectors: the default method will
only return a non-negative integer (and never NA), but
see section ‘Warning’.
On the other hand, the default method for xlength will return a
double value for vectors of more than 2^31 - 1
elements, and the default replacement method can set the length of
atomic vectors and list to such a length if value is double.
For vectors (including lists) and factors the length is the number of
elements. For an environment it is the number of objects in the
environment, and NULL has length 0. For expressions and
pairlists (including language objects and dotlists) it is the length
of the pairlist chain. All other objects (including functions) have
length one: note that for functions this differs from S.
The replacement forms remove all the attributes of x except its
names.
Package authors have written methods that return a result of
length other than one (Formula) and that return a vector type
double (Matrix), even with non-integer values
(sets). As from R 2.16.0, where a single double value is
returned that can be represented as an integer, it is returned as a
length-one integer vector.
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.
nchar for counting the number of characters in
character vectors.
length(diag(4))# = 16 (4 x 4)
length(options())# 12 or more
length(y ~ x1 + x2 + x3)# 3
length(expression(x, {y <- x^2; y+2}, x^y)) # 3
## from example(warpbreaks)
require(stats)
fm1 <- lm(breaks ~ wool * tension, data = warpbreaks)
length(fm1$call) # 3, lm() and two arguments.
length(formula(fm1)) # 3, ~ lhs rhs