user12027316
user12027316

Reputation: 123

Return the max number of elements in a list of variously sized arrays

My goal is to write a simple function that accepts a list of an indefinite amount of arrays (and elements can be strings or numbers) and returns the number of elements in the array with the most elements.

In the list:

x <- list(c(1,2,3,4,5),
          c(1,2,3),
          c(1,2,3,4,5,6,7))

The answer would be 7 because the third array has the max amount of elements in the list.

Conceptually, I'm having a hard time applying the idea of element count to a singular array within a list. When I try, like in the example below, I count the number of all elements. The difficulty is that I can't use a loop to solve it, only functions like sapply() or built in functions - no importing or calling from other libraries. How do I count the number of elements in each array in a list and then use max() on it?

listMax <- function(x) {
  findMax <- sum(sapply(x,length))
  print(findMax)
}

Upvotes: 0

Views: 79

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

You can use lengths to count length of each element in the list and then use max

max(lengths(x))
#[1] 7

Upvotes: 3

Daniel V
Daniel V

Reputation: 1386

max(unlist(lapply(x, length)))

Upvotes: 1

Related Questions