Reputation: 1
For example, I have this data frame:
id name date
1 susan 1/1/2020
2 jhon 1/1/2020
3 susan 1/1/2020
4 eric 2/4/2020
5 eric 2/4/2020
6 susan 2/1/2020
7 eric 2/4/2020
And I need this:
id name date output
1 susan 1/1/2020 1
2 jhon 1/8/2020 1
3 susan 1/1/2020 2
4 eric 2/4/2020 1
5 eric 2/4/2020 2
6 susan 2/9/2019 1
7 eric 2/4/2020 3
The output column is possible in excel with COUNTIF function, but I need this using R.
I group by name and date.
Upvotes: 0
Views: 62
Reputation: 1
This is the answer:
with(dataframe, ave(seq_along(name), name, date, FUN=seq_along))
from this post: R enumerate duplicates in a dataframe with unique value
thanks for the other answers.
Upvotes: 0
Reputation: 12739
Thanks for the clarification.
Does this give you what you want?
# data
tib <- tibble( name = c("susan", "jhon", "susan", "eric", "eric", "susan", "eric"),
date = c("1/1/2020", "1/1/2020", "1/1/2020", "2/4/2020", "2/4/2020", "2/1/2020", "2/4/2020"))
# datawrangle
tib1 <-
tib %>%
group_by(name, date) %>%
mutate(output = row_number())
Which results in:
tib1
## # A tibble: 7 x 3
## # Groups: name, date [4]
## name date output
## <chr> <chr> <int>
## 1 susan 1/1/2020 1
## 2 jhon 1/1/2020 1
## 3 susan 1/1/2020 2
## 4 eric 2/4/2020 1
## 5 eric 2/4/2020 2
## 6 susan 2/1/2020 1
## 7 eric 2/4/2020 3
Upvotes: 1