简体   繁体   中英

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

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

What about length(unlist(whatever)) ?

(Note: I just wanted to reply that there's no such function, but suddenly I recalled I just used unlist 30 minutes ago, and that it can be applied to get easy solution! What a coincidence...)

My personal 'convenience function' for this is:

Rgames: lssize
function(items){
sizes<-sapply(sapply(sapply(sapply(items,get,simplify=F),unlist,simplify=F),as.vector,simplify=F),length)
return(sizes)
    }

It works on every 'typeof' variable I could think of. FWIW, it's part of my toolkit which includes the useful "find only one type of variable in my workspace" :

Rgames: lstype
function(type='closure'){
    inlist<-ls(.GlobalEnv)
    if (type=='function') type <-'closure'
    typelist<-sapply(sapply(inlist,get),typeof)
    return(names(typelist[typelist==type]))

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM