2

From a dataframe of 4960 rows, which one is countries, I filtered the top five that appear the most this way, and it works perfectly.

sort(table(gtd$country_txt), decreasing = TRUE)[1:5]

Now I want to grab all the data from those by subsetting. I already found the way to get 1, but not the 5.

gtd_top <- subset(gtd, country_txt == "Afghanistan")

It should be Afghanistan, Iraq, Nigeria, Yemen, and India.

Would be better to merge all in 1 function.

neilfws
  • 32,751
  • 5
  • 50
  • 63

1 Answers1

2

Consider passing the names from that sorted vector generated from table into subset using %in%:

top_five <- sort(table(gtd$country_txt), decreasing=TRUE)[1:5]

gtd_top <- subset(gtd, country_txt %in% names(top_five))
Parfait
  • 104,375
  • 17
  • 94
  • 125