Get the longest list item

Suppose you have a data.frame list 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))
)

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

I am stuck at this point:

library(plyr)
lengths <- lapply(dfs, nrow)
longest <- max(lengths)
+4
source share
2 answers

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

  • which.max: returns the index of the first element of your list, which is max

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

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

Then you can multiply your list by the desired item:

dfs[which(lengths==longest)]

will return b and c to your example.

+6
source
cnt <- sapply(dfs, nrow)
dfs[cnt == max(cnt)]

Or, if you only need the first occurrence of the maximum length:

dfs[which.max(cnt)]
+4
source

Source: https://habr.com/ru/post/1623950/


All Articles