Reputation: 1
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))
How to find which vectors have the highest number of elements? For example for this code above my result should be "vec2 and vec4". But when I use which.max()
, it only returns "vec2".
Upvotes: 0
Views: 51
Reputation: 32548
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
Upvotes: 1
Reputation: 145775
# 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)
Upvotes: 1