I applied sum() on a groupby and I want to sort the values of the last column

前端 未结 2 1018
名媛妹妹
名媛妹妹 2021-01-14 03:17

Given the following DataFrame

user_ID  product_id  amount
   1       456          1
   1        87          1
   1       788          3
   1       456                


        
2条回答
  •  猫巷女王i
    2021-01-14 04:22

    You could also use aggregate():

    # Make up some example data
    df = data.frame (user_ID = as.factor(rep(1:5, each = 5)), 
                     product_id = as.factor(sample(seq(1:10),size = 25, replace = TRUE)),
                     amount = sample(1:5, size = 25, replace = TRUE))
    
    # Use aggregate with function sum to calculate the amount of products bought by product and customer
    aggregate(amount ~  product_id * user_ID , data = df, FUN = sum)
    

    Output:

       product_id user_ID amount
    1           2       1      3
    2           4       1      2
    3           6       1      1
    4           9       1      5
    5           1       2      5
    6           3       2      9
    7           8       2      1
    8          10       2      5
    9           2       3      5
    10          3       3      5
    11          4       3      5
    12          5       3      3
    13          8       3      5
    14          3       4      3
    15          4       4      9
    16          5       4      2
    17         10       4      1
    18          2       5      1
    19          4       5      4
    20          5       5      2
    21         10       5      2
    

提交回复
热议问题