Search code examples
rdplyrslice

Using mutate and slice_max in dplyr


I have the following dataframe:

df=data.frame(defect= 
                        c("defect1","defect2","defect3","defect4","defect5","defect6","defect7",
                          "defect8","defect9","defect10","defect11","defect12","defect13"),
                      num=c(1,2,5,10,20,25,35,45,60,70,3,4,5))
 

and I want to use mutate and slice_max to get the top 5 and top 10 defects but this doesn't work:

df%>%
  summarise(Defect_list_top_5=paste0(slice_max(num,n=5)," ",num, collapse="|"),
            Defect_list_top_10=paste0(slice_max(num,n=5)," ",num, collapse="|"))

I know how to do it this way and the final represents what I expect the output to be:

 x=df%>%
  slice_max(num,n=5)%>%
  summarise(Defect_list_top_5=paste0(defect," ",num, collapse = "|"))
  
y=df%>%
  slice_max(num,n=10)%>%
  summarise(Defect_list_top_10=paste0(defect," ",num, collapse = "|"))

final=cbind(x,y)

Solution

  • df %>%
        slice_max(num, n = 10) %>%
        summarise(top_5 = paste(defect[1:5],collapse = "|"),
                            top_10 = paste(defect, collapse = "|"))