Reputation: 36547
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.
Upvotes: 4
Views: 2633
Reputation: 176648
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
Upvotes: 6
Reputation: 21502
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]))
}
Upvotes: 1
Reputation: 59483
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...)
Upvotes: 5