[英]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? 是否有内置的便捷函数返回data.frame,matrix或vector中的元素数量?
length( matrix )
and length( vector )
work, but length( data.frame )
returns the number of columns. length( matrix )
和length( vector )
工作,但length( data.frame )
返回列数。 prod( dim( vector ) )
returns 1 always, but works fine with matrix/data.frame. prod( dim( vector ) )
总是返回1,但是对于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:
您应该只需要2个案例,1)列表,2)数组:
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))
? length(unlist(whatever))
怎么样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...) (注意:我只想回答说没有这样的功能,但我突然想起我刚刚在30分钟前使用过unlist,并且可以应用它来获得简单的解决方案!真是巧合...)
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. 它适用于我能想到的每个'typeof'变量。 FWIW, it's part of my toolkit which includes the useful "find only one type of variable in my workspace" :
FWIW,它是我的工具包的一部分,其中包括有用的“在我的工作区中只查找一种类型的变量”:
Rgames: lstype
function(type='closure'){
inlist<-ls(.GlobalEnv)
if (type=='function') type <-'closure'
typelist<-sapply(sapply(inlist,get),typeof)
return(names(typelist[typelist==type]))
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.