Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convenience function for # elements in data.frame, matrix, vector?

Tags:

r

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.

like image 663
SFun28 Avatar asked Dec 17 '22 08:12

SFun28


1 Answers

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
like image 146
Joshua Ulrich Avatar answered Jan 30 '23 23:01

Joshua Ulrich