Search code examples
rpercentile

ntile function not working in latest version of R


My data is

my_basket <- data.frame(ITEM_GROUP = c("Fruit","Fruit","Fruit","Fruit","Fruit","Vegetable","Vegetable","Vegetable","Vegetable","Dairy","Dairy","Dairy","Dairy","Dairy"), 
                       ITEM_NAME = c("Apple","Banana","Orange","Mango","Papaya","Carrot","Potato","Brinjal","Raddish","Milk","Curd","Cheese","Milk","Paneer"),
                       Price = c(100,80,80,90,65,70,60,70,25,60,40,35,50,120)) 

I would like to calculate a column for percentiles using the ntile function

df1 = mutate(my_basket, percentile_rank = ntile(my_basket$Price,100))

It should give me a dataframe that looks like correct_df

correct_df<- data.frame(ITEM_GROUP = c("Fruit","Fruit","Fruit","Fruit","Fruit","Vegetable","Vegetable","Vegetable","Vegetable","Dairy","Dairy","Dairy","Dairy","Dairy"), 
                       ITEM_NAME = c("Apple","Banana","Orange","Mango","Papaya","Carrot","Potato","Brinjal","Raddish","Milk","Curd","Cheese","Milk","Paneer"),
                       Price = c(100,80,80,90,65,70,60,70,25,60,40,35,50,120),
                       percentile_rank=c(86,65,72,79,43,51,29,58,1,36,15,8,22,93))

But instead I get a dataframe that looks like wrong_df

wrong_df<- data.frame(ITEM_GROUP = c("Fruit","Fruit","Fruit","Fruit","Fruit","Vegetable","Vegetable","Vegetable","Vegetable","Dairy","Dairy","Dairy","Dairy","Dairy"), 
                        ITEM_NAME = c("Apple","Banana","Orange","Mango","Papaya","Carrot","Potato","Brinjal","Raddish","Milk","Curd","Cheese","Milk","Paneer"),
                        Price = c(100,80,80,90,65,70,60,70,25,60,40,35,50,120),
                        percentile_rank=c(13,10,11,12,7,8,5,9,1,6,3,3,4,14)) 

This issue has only come up since I updated my R version to 4.0.2


Solution

  • I don't think this is an R issue but seems to be an issue with dplyr 1.0.0 as mentioned in this open GitHub issue. See the difference in the output of two functions taken from there.

    ntile_083(my_basket$Price,100)
    #[1] 86 65 72 79 43 51 29 58  1 36 15  8 22 93
    ntile_100(my_basket$Price,100)
    #[1] 13 10 11 12  7  8  5  9  1  6  3  2  4 14
    

    You can use ntile_083 to get the previous functionality for now.