vec1 <- c(1,2,3)
vec2 <- c(10,20,30,40,100,200)
vec4 <- c(1,2,3,4,5,6)
a <- c("vec1"=length(vec1),"vec2"=length(vec2),"vec4"=length(vec4))
如何查找哪些向量的元素数最多?例如,对于上面的这段代码,我的结果应为“ vec2和vec4”。但是当我使用which.max()
时,它仅返回“ vec2”。
答案 0 :(得分:1)
# put the vectors in a list
vec_list = list(vec1 = vec1, vec2 = vec2, vec4 = vec4)
# calculate the lengths of each
vec_length = lengths(vec_list)
# see which one has the max length - this will stop at the first maximum
which.max(vec_length)
# vec2
# 2
## include ties like this:
which(vec_length == max(vec_length))
# vec2 vec4
# 2 3
## this gives both the names (as the names of the result)
## and the indices (values of the result)
答案 1 :(得分:1)
foo = function(...) {
nm = as.character(as.list(match.call()[-1L]))
len = lengths(list(...))
ind = which(len == max(len))
setNames(len[ind], nm[ind])
}
foo(vec1, vec2, vec4)
#vec2 vec4
# 6 6