2

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)
Nathalie
  • 1,228
  • 7
  • 20
  • The output you want does not match with the output of the answer you marked. Have a look and double check. If the marked answer is your desired then this question is a duplicate and I will mark it as such. – Sotos Jul 07 '20 at 06:27

2 Answers2

1

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
Daniel O
  • 4,258
  • 6
  • 20
  • @Sotos. After closer inspection, you are right that my output does not match the desired output. I do not understand what the expected output even represents. Either OP made an error in what she truly desired, or she made an error in accepting my answer. – Daniel O Jul 06 '20 at 19:13
1

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
Sotos
  • 51,121
  • 6
  • 32
  • 66