Is there a built-in convenience function that returns the number of elements in a data.frame, matrix, or vector? length( matrix )
and length( vector )
work, but length( data.frame )
returns the number of columns. prod( dim( vector ) )
returns 1 always, but works fine with matrix/data.frame. I'm looking for a single function that works for all three.
I don't think one already exists, so just write your own. You should only need 2 cases, 1) lists, 2) arrays:
elements <- function(x) {
if(is.list(x)) {
do.call(sum,lapply(x, elements))
} else {
length(x)
}
}
d <- data.frame(1:10, letters[1:10])
m <- as.matrix(d)
v <- d[,1]
l <- c(d, list(1:5))
L <- list(l, list(1:10))
elements(d) # data.frame
# [1] 20
elements(m) # matrix
# [1] 20
elements(v) # vector
# [1] 10
elements(l) # list
# [1] 25
elements(L) # list of lists
# [1] 35
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With