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
  • 37,241
  • 25
  • 195
  • 267
NBC
  • 1,606
  • 4
  • 18
  • 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
  • 37,904
  • 9
  • 56
  • 69
4

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
  • 209,562
  • 33
  • 339
  • 356