kin182
kin182

Reputation: 403

How to find top n common elements in a list?

I am relatively new to R and I am trying to find the top 3 elements in the data frame in a list. For example, I have a list like this

Combined <- list(L1 <- mtcars[1:6,], 
                 L2 <- mtcars[2:7,],
                 L3 <- mtcars[3:8,],
                 L4 <- mtcars[4:9,],
                 L5 <- mtcars[5:10,])

I aim to return the top 3 common rownames in decreasing order, like

[1] "Hornet Sportabout"    "Valiant"     "Duster 360"

Any help is appreciated. Thanks!

Upvotes: 1

Views: 47

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

Create a new column with rownames in each list, combine them in one dataframe, count each rownames and return top 3.

library(dplyr)

purrr::map_df(Combined, tibble::rownames_to_column) %>%
  count(rowname) %>%
  slice_max(n = 3, n, with_ties = FALSE) %>%
  pull(rowname)

#[1] "Hornet Sportabout" "Valiant"           "Duster 360" 

Upvotes: 1

IRTFM
IRTFM

Reputation: 263342

I think this is what is desired. You are gathering the rownames of those list items, tabulating and sorting.

sort( table( c( sapply(Combined, rownames) ) ),
      decreasing=TRUE ) [1:3]
#---------------------------
Hornet Sportabout           Valiant        Duster 360 
                5                 5                 4 

If you just want the character values then wrap names around that result.

names( sort( table( c( sapply(Combined, rownames) ) ), 
             decreasing=TRUE ) [1:3] )
#[1] "Hornet Sportabout" "Valiant"           "Duster 360"       

Upvotes: 2

Related Questions