Nathalie
Nathalie

Reputation: 1238

How to extract frequency per datetime stamp

From a data frame as month and a continuous number id

data.frame( id = c(1,1,2,2,3), month = c("2011-02","2011-02","2011-02","2011-03","2011-01"))

How is it possible to extract the total number of month and have the frq for every id? Expected output:

data.frame(id = c(1,2,2,3), month = c("2011-02","2011-02","2011-03","2011-01"), frq = c(1,1,2,1)

Upvotes: 2

Views: 65

Answers (2)

Sotos
Sotos

Reputation: 51592

An idea via dplyr can be,

library(dplyr)

distinct(df) %>% 
  group_by(id) %>% 
  mutate(freq = seq(n()))


# A tibble: 4 x 3
# Groups:   id [3]
#     id month    freq
#  <dbl> <fct>   <int>
#1     1 2011-02     1
#2     2 2011-02     1
#3     2 2011-03     2
#4     3 2011-01     1

Upvotes: 1

Daniel O
Daniel O

Reputation: 4358

one option is:

df$freq <- 1
aggregate(freq  ~ id + month, df, sum)
  id   month freq
1  3 2011-01    1
2  1 2011-02    2
3  2 2011-02    1
4  2 2011-03    1

Upvotes: 1

Related Questions