Description Usage Arguments Details Value Note See Also Examples
Get the length of each element of a list
or atomic
vector (is.atomic
) as an integer or numeric vector.
1 |
x |
a |
use.names |
logical indicating if the result should inherit the
|
This function loops over x
and returns a compatible vector
containing the length of each element in x
. Effectively,
length(x[[i]])
is called for all i
, so any methods on
length
are considered.
A non-negative integer
of length length(x)
,
except when any element has a length of more than
2^31 - 1 elements, when it returns a double vector.
When use.names
is true, the names are taken from the names on
x
, if any.
One raison d'ĂȘtre of lengths(x)
is its use as a
more efficient version of sapply(x, length)
and similar
*apply
calls to length
. This is the reason why
x
may be an atomic vector, even though lengths(x)
is
trivial in that case.
length
for getting the length of any R object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | require(stats)
## summarize by month
l <- split(airquality$Ozone, airquality$Month)
avgOz <- lapply(l, mean, na.rm=TRUE)
## merge result
airquality$avgOz <- rep(unlist(avgOz, use.names=FALSE), lengths(l))
## but this is safer and cleaner, but can be slower
airquality$avgOz <- unsplit(avgOz, airquality$Month)
## should always be true, except when a length does not fit in 32 bits
stopifnot(identical(lengths(l), vapply(l, length, integer(1L))))
## empty lists are not a problem
x <- list()
stopifnot(identical(lengths(x), integer()))
## nor are "list-like" expressions:
lengths(expression(u, v, 1+ 0:9))
## and we should dispatch to length methods
f <- c(rep(1, 3), rep(2, 6), 3)
dates <- split(as.POSIXlt(Sys.time() + 1:10), f)
stopifnot(identical(lengths(dates), vapply(dates, length, integer(1L))))
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.