如何在R中使用Group By和order函数

Ran*_*dey 2 sorting group-by r data.table

我有一个包含120000条记录和19个变量的数据框,其中2个是state和MonthlyIncome.

我必须创建一个新的数据集,其中包含来自每个州的前10名(月收入)客户.

我尝试了很多选项,包括data.table和dplyr以及base,但总会有一些缺失.

data.table:

 x <- customer_any_360[,order(-dense_rank(MonthlyIncome))[1:10], by = state]
Run Code Online (Sandbox Code Playgroud)

---我试过的例子

有人可以请求帮助,我仍然是R的新手并且真的在努力解决这个问题.提前致谢!!

akr*_*run 8

如果要使用rank函数,可以frankdata.table其中指定一个选项ties.method.

library(data.table)#v1.9.5+
setDT(customer_any_360)[, .SD[frank(-MonthlyIncome, 
               ties.method='dense') %in% 1:10], by = state]
Run Code Online (Sandbox Code Playgroud)

或者甚至就order足够了

setDT(customer_any_360)[order(-MonthlyIncome), .SD[1:10], by = state]
Run Code Online (Sandbox Code Playgroud)

使用dplyr,有复式的选择,dense_rank,min_rank,top_n这取决于你想要的东西.另外,用于过滤,slice或者filter可以使用.

library(dplyr)
customer_any_360 %>%
           group_by(state) %>%
           slice(dense_rank(-MonthlyIncome)[1:10])
Run Code Online (Sandbox Code Playgroud)

或使用 sqldf

 library(sqldf)
 sqldf('select * from customer_any_360 i
          where rowid in 
          (select rowid from customer_any_360 
           where state = i.state 
           order by MonthlyIncome desc 
           limit 10)
  order by i.state, i.MonthlyIncome desc')
Run Code Online (Sandbox Code Playgroud)

或者使用ave来自base R

indx <- with(customer_any_360, ave(-MonthlyIncome, state,
       FUN=function(x) rank(x, ties.method='first')) %in% 1:10)
customer_any_360[indx,]
Run Code Online (Sandbox Code Playgroud)

编辑:该frank选项是根据@Arun的建议编辑的

数据

set.seed(24)
customer_any_360 <- data.frame(cust=1:120000, state= sample(state.abb,
  120000, replace=TRUE), MonthlyIncome= sample(1000:6500, 120000, 
     replace=TRUE), stringsAsFactors=FALSE)
Run Code Online (Sandbox Code Playgroud)