1
df <- data.frame(name=c('black','black','black','red','red'),
                 type=c('chair','chair','sofa','sofa','sofa'),
                 num=c(4,4,12,4,6))

For each row, I want to count the number of times that "type" appears with that row's num value, and then create a new column. So for the first row, "chair" and "num" appears twice in the dataset, so it gets assigned a 2. For the second row, same thing. For the 3rd row, sofa appears once with a value of 12.

df
#    name  type num count
# 1 black chair   4     2
# 2 black chair   4     2
# 3 black  sofa  12     1
# 4   red  sofa   4     1
# 5   red  sofa   6     1
Cœur
  • 34,719
  • 24
  • 185
  • 251
NBC
  • 1,506
  • 4
  • 15
  • 31

2 Answers2

7

Using ave in base R, you have

df$count <- with(df, ave(num, name, type, num, FUN=length))

Get the length of num, grouping by name, type, and num. Use with to reduce typing a bit.

this returns

df
   name  type num count
1 black chair   4     2
2 black chair   4     2
3 black  sofa  12     1
4   red  sofa   4     1
5   red  sofa   6     1
lmo
  • 36,904
  • 9
  • 50
  • 61
3

Use dplyr::add_count:

dplyr::add_count(df, type, num)

# A tibble: 5 x 4
#    name   type   num     n
#  <fctr> <fctr> <dbl> <int>
#1  black  chair     4     2
#2  black  chair     4     2
#3  black   sofa    12     1
#4    red   sofa     4     1
#5    red   sofa     6     1
Psidom
  • 195,464
  • 25
  • 298
  • 322