0

this should be fairly simple but I just can't get my head around it.

I have the following dataframe,

df <- data.frame(Type = c(rep('type1',3),rep('type2',2),rep('type3',3)))

I want to aggregate, and then start with a 1-value, and increase it once the group changes, having the following output:

df2 <- data.frame(Type = c(rep('typea',3),rep('typeb',2),rep('typec',3)), new_var = c(1,1,1,2,2,3,3,3))

Long story short, I am looking to count groups and add them to the right of the dataframe.

oscartorom
  • 92
  • 7

1 Answers1

1

In ?dplyr::context (not the first place I might look when search for this, but ... I searched for related topics and found that help page), they list several helper functions that are available within a dplyr verb, and can identity some properties of the current group or such. Included in this list of context functions:

  • n()
  • cur_data() and cur_data_all()
  • cur_group() (same class as the grouping variable(s)) and cur_group_id() (integer)
  • cur_group_rows()
  • cur_column() (useful within across actions)
df %>%
  group_by(Type) %>%
  mutate(new_var = cur_group_id()) %>%
  ungroup()
# # A tibble: 8 x 2
#   Type  new_var
#   <chr>   <int>
# 1 type1       1
# 2 type1       1
# 3 type1       1
# 4 type2       2
# 5 type2       2
# 6 type3       3
# 7 type3       3
# 8 type3       3
r2evans
  • 141,215
  • 6
  • 77
  • 149