0

I have the following data frame:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6))

and I want to record the number of occurrences of each category so the output would be:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6), 
category_count=c(2,4,4,4,4,2,1))

Is there a simple way to do this?

camille
  • 15,634
  • 17
  • 33
  • 53
David_G
  • 67
  • 4

3 Answers3

0
# load package
library(data.table)

# set as data.table
setDT(df)

# count by category
df[, category_count := .N, category]
Sweepy Dodo
  • 1,522
  • 8
  • 13
0

With dplyr:

library(dplyr)

df %>%
        group_by(category) %>%
        mutate(category_count = n()) %>%
        ungroup

# A tibble: 7 × 3
  category value category_count
  <chr>    <dbl>          <int>
1 a            1              2
2 b            5              4
3 b            3              4
4 b            6              4
5 b            7              4
6 a            4              2
7 c            6              1
GuedesBF
  • 5,927
  • 5
  • 12
  • 31
0

base

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6), 
                 category_count=c(2,4,4,4,4,2,1))

df$res <- with(df, ave(x = seq(nrow(df)), list(catergory), FUN = length))
df
#>   catergory value category_count res
#> 1         a     1              2   2
#> 2         b     5              4   4
#> 3         b     3              4   4
#> 4         b     6              4   4
#> 5         b     7              4   4
#> 6         a     4              2   2
#> 7         c     6              1   1

Created on 2022-02-08 by the reprex package (v2.0.1)

Yuriy Saraykin
  • 7,360
  • 1
  • 6
  • 12