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)
In this, we use inbuilt max() with “len” as key argument to extract the string with the maximum length.
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.
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 .
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.
There are two built-in functions in R that could solve your question in my opinion:
which.max
: returns the index of the first element of your list that is equal to the max
> which.max(lengths)
[1] 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With