Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the longest element of a list

Tags:

list

r

Suppose you have a list of data.frames like

dfs <- list(
  a = data.frame(x = c(1:4, 7:10), a = runif(8)),
  b = data.frame(x = 1:10, b = runif(10)),
  c = data.frame(x = 1:10, c = runif(10))
)

I would now like to extract the longest data.frame or data.frames in this list. How?

I am stuck at this point:

library(plyr)
lengths <- lapply(dfs, nrow)
longest <- max(lengths)
like image 549
vanao veneri Avatar asked Jan 12 '16 15:01

vanao veneri


People also ask

How do you find the maximum length of an element in a list Python?

In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length.

How do you find the longest word in a list Python?

Find the length of the longest word using the len() (The number of items in an object is returned by the len() method. It returns the number of characters in a string when the object is a string) and max() (returns the highest-valued item, or the highest-valued item in an iterable) functions from the above words list.

How do you find the length of the longest string in a list?

Use max() to find the longest string in a list. Call max(a_list, key=len) to return the longest string in a_list by comparing the lengths of all strings in a_list .

How do I print the longest list in Python?

Method 1: max(lst, key=len) Use Python's built-in max() function with a key argument to find the longest list in a list of lists. Call max(lst, key=len) to return the longest list in lst using the built-in len() function to associate the weight of each list, so that the longest inner list will be the maximum.


1 Answers

There are two built-in functions in R that could solve your question in my opinion:

  1. which.max: returns the index of the first element of your list that is equal to the max

    > which.max(lengths)
    [1] 2
    
  2. which function returns all indexes that are TRUE Here:

    > which(lengths==longest)
    [1] 2 3 
    

Then you can subset you list to the desired element:

dfs[which(lengths==longest)]

will return b and c in your example.

like image 54
DeveauP Avatar answered Sep 28 '22 20:09

DeveauP