add a column with the sum of quantity

Hello,

About this data frame:

df <- data.frame(id = c("1-1","1-1","1-1","1-1","1-1","1-1","1-1","1-1",
                          "1-1","1-1", "1-1","1-1","1-1","1-1","1-1",
                          "2-2","2-2","2-2","2-2","2-2"),
                   group = c(1,1,1,2,2,3,3,3,4,4,5,
                             5,5,5,5,
                             5,5,5,7,8),
                   product = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,
                               15,16,17, 18, 19, 20),
                   client = c("90-1", "90-1","90-1","90-1","90-1","90-1","90-1",
                            "90-1","90-1","90-1","90-1","90-1","90-2","90-2",
                            "90-2","90-2","90-2","90-3","90-3","90-3"))

How can you add a mutate() that can sum() the quantity of client
12 because are 12 clients
5 because are 5 clients
3 because are 3 clients.

An output like this:

link

Thanks!

This is easily done with the n() function which counts the number of rows in a group.

df <- data.frame(id = c("1-1","1-1","1-1","1-1","1-1","1-1","1-1","1-1",
                        "1-1","1-1", "1-1","1-1","1-1","1-1","1-1",
                        "2-2","2-2","2-2","2-2","2-2"),
                 group = c(1,1,1,2,2,3,3,3,4,4,5,
                           5,5,5,5,
                           5,5,5,7,8),
                 product = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,
                             15,16,17, 18, 19, 20),
                 client = c("90-1", "90-1","90-1","90-1","90-1","90-1","90-1",
                            "90-1","90-1","90-1","90-1","90-1","90-2","90-2",
                            "90-2","90-2","90-2","90-3","90-3","90-3"))
library(dplyr)

df <- df |> group_by(client) |> mutate(N = n())
df
#> # A tibble: 20 × 5
#> # Groups:   client [3]
#>    id    group product client     N
#>    <chr> <dbl>   <dbl> <chr>  <int>
#>  1 1-1       1       1 90-1      12
#>  2 1-1       1       2 90-1      12
#>  3 1-1       1       3 90-1      12
#>  4 1-1       2       4 90-1      12
#>  5 1-1       2       5 90-1      12
#>  6 1-1       3       6 90-1      12
#>  7 1-1       3       7 90-1      12
#>  8 1-1       3       8 90-1      12
#>  9 1-1       4       9 90-1      12
#> 10 1-1       4      10 90-1      12
#> 11 1-1       5      11 90-1      12
#> 12 1-1       5      12 90-1      12
#> 13 1-1       5      13 90-2       5
#> 14 1-1       5      14 90-2       5
#> 15 1-1       5      15 90-2       5
#> 16 2-2       5      16 90-2       5
#> 17 2-2       5      17 90-2       5
#> 18 2-2       5      18 90-3       3
#> 19 2-2       7      19 90-3       3
#> 20 2-2       8      20 90-3       3

Created on 2023-09-08 with reprex v2.0.2

1 Like

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.