-1

Here is my dataframe:

Number    Action
1         Running
2         Running
3         Swimming
4         Eating
5         Eating

I would like to add a variable to count the number of appearance, like this:

Number    Action    Count
1         Running   1
2         Running   2
3         Swimming  1
4         Eating    1
5         Eating    2
xxx
  • 53
  • 1
  • 6
  • Next time please try and make your question reproducible by including the data using `dput(data)` and include what you have already tried – morgan121 Nov 27 '18 at 01:08

1 Answers1

0

Here's a way using dplyr

library(dplyr)

df <- data.frame(Number = c(1, 2, 3, 4, 5), 
                 Action = c("Running",  "Running", "Swimming", "Eating", "Eating"))

df %>% 
  group_by(Action) %>% 
  mutate(Count = row_number())

#> # A tibble: 5 x 3
#> # Groups:   Action [3]
#>   Number Action   Count
#>    <dbl> <chr>    <int>
#> 1      1 Running      1
#> 2      2 Running      2
#> 3      3 Swimming     1
#> 4      4 Eating       1
#> 5      5 Eating       2

Created on 2018-11-26 by the reprex package (v0.2.1)

Jake Kaupp
  • 7,892
  • 2
  • 26
  • 36