Filter() row number in dplyr not working

Hello community, i'm having an issue with filter and I can't tell what's wrong.

Here is my code:

contracts_15<-contracts_month
contracts_15_1<-contracts_15 %>% 
  dplyr::select(name_contract, entity, object, total,  initial_date, end_date,type_dummy,mode)
contracts_15_2<-contracts_15_1%>%
  dplyr::group_by(name_contract)

contracts_15_3<-contracts_15_2 %>%
  dplyr::filter(total>15000000)%>% 
  arrange(-total)

contracts_15_4<-contracts_15_3 %>% 
  filter(row_number() <= 10, row_number() >= 1)

write.xlsx(contracts_15_4, "03_Output/Nov2023/contracts_15.xlsx")
  1. I've got a list of contracts signed on november.
  2. I selected some columns I want.
  3. I grouped them by contract name
  4. Then i want to filter them to get "over $15 million" ones.

Up to that point, everything is ok. Then, when I want to get my "top 10" of contracts for some reason it doesnt work getting the same number of rows, 27, in this case.

I tried this test and worked properly, what do you think i did wrong in my previous code?
the grouping?

n = c(1:10)
s = c("aa","mexico","italia","camerun","texas","argentina","guatemala","frankfurt","amigos","jose")
b = c(555655,554541,445548,21035,45451421,54542,5452,5454224,4200964,54214)
test1 = data.frame(n,s,b)

test2<-test1 %>%
  dplyr::filter(b>150000)%>% 
  arrange(-b)

test3<-test2 %>% 
  filter(row_number() <= 3, row_number() >= 1)

Hi @coronelgavilan. Yes, you need to ungroup before taking the overall top10.

contracts_15_4<-contratos_15_3 %>% 
  ungroup() %>%
  filter(row_number() <= 10, row_number() >= 1)
1 Like

Thanks Scott! solved it

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.