radditioncalculated-columnsfind-occurrencesmultiple-occurrence

adding a column to df that counts occurrence of a value in another column


What I am trying to do is adding a column by "places" that count the id occurrence in the whole column "id' :

 id <- c(204850, 204850, 204850,312512,312512,452452,285421,758412,758412,758412)
places <- c("kitchen","kitchen","garden","salon","salon","salon","bathroom","garden","bathroom","garden")
 df <- data.frame(id, places)
 

    > df
           id   places
    1  204850  kitchen
    2  204850  kitchen
    3  204850   garden
    4  312512    salon
    5  312512    salon
    6  452452    salon
    7  285421 bathroom
    8  758412   garden
    9  758412 bathroom
    10 758412   garden

the only option I saw is by count in dplyr but it is create a new data frame.

The output should look like this:

> df
       id   places id_occurrence
1  204850  kitchen             3
2  204850  kitchen             3
3  204850   garden             3
4  312512    salon             2
5  312512    salon             2
6  452452    salon             1
7  285421 bathroom             1
8  758412   garden             3
9  758412 bathroom             3
10 758412   garden             3

Solution

  • You can use the following solution:

    library(dplyr)
    
    df %>%
      group_by(id) %>%
      add_count(name = "id_occurrence")
    
    # A tibble: 10 x 3
    # Groups:   id [5]
           id places   id_occurrence
        <dbl> <chr>            <int>
     1 204850 kitchen              3
     2 204850 kitchen              3
     3 204850 garden               3
     4 312512 salon                2
     5 312512 salon                2
     6 452452 salon                1
     7 285421 bathroom             1
     8 758412 garden               3
     9 758412 bathroom             3
    10 758412 garden               3