Home > Mobile >  Ways to check if all sublists have the same length/number of elements?
Ways to check if all sublists have the same length/number of elements?

Time:10-22

The main list can be dynamically created (i.e., the number of sublists may vary) so I cannot use all.equal or simply compare the lengths.

In this attached photo for example, you can see that I have three sublists. How can I check if they have the same number of characters or list length(which in this case they do not)?

CodePudding user response:

One way is to use lengths and check if the number of distinct elements are equal to 1 or not

dplyr::n_distinct(lengths(main_list)) == 1

n_distinct will be just length(unique( in base R

length(unique(lengths(main_list))) == 1
  • Related