Within dplyr
你需要arrange()
by ID
and VAR
进而group_by()
just ID
.
然后你使用mutate()
添加新列,从 1 数到n()
(where n()
是“行数”的 dplyr 函数)
set.seed(123)
dt %>%
arrange(ID, VAR) %>%
group_by(ID) %>%
mutate(COUNTER = 1:n()) %>% ## as per comment, can use row_number()
ungroup()
# # A tibble: 12 × 3
# ID VAR COUNTER
# <fctr> <int> <int>
# 1 a 29 1
# 2 a 41 2
# 3 a 79 3
# 4 a 86 4
# 5 b 29 1
# 6 b 41 2
# 7 b 79 3
# 8 b 86 4
# 9 c 29 1
# 10 c 41 2
# 11 c 79 3
# 12 c 86 4
关于取消分组的评论
我这样做是为了删除与某个关联的所有“分组”属性grouped_df
。在此示例中,结果是相同的,但这些分组的属性可能会进一步影响您。
dt_grouped <- dt %>%
arrange(ID, VAR) %>%
group_by(ID) %>%
mutate(COUNTER = 1:n())
dt_ungrouped <- dt %>%
arrange(ID, VAR) %>%
group_by(ID) %>%
mutate(COUNTER = 1:n()) %>%
ungroup()
str(dt_grouped)
# Classes ‘grouped_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 12 obs. of 3 variables:
# $ ID : Factor w/ 3 levels "a","b","c": 1 1 1 1 2 2 2 2 3 3 ...
# $ VAR : int 29 41 79 86 29 41 79 86 29 41 ...
# $ COUNTER: int 1 2 3 4 1 2 3 4 1 2 ...
# - attr(*, "vars")=List of 1
# ..$ : symbol ID
# - attr(*, "labels")='data.frame': 3 obs. of 1 variable:
# ..$ ID: Factor w/ 3 levels "a","b","c": 1 2 3
# ..- attr(*, "vars")=List of 1
# .. ..$ : symbol ID
# ..- attr(*, "drop")= logi TRUE
# - attr(*, "indices")=List of 3
# ..$ : int 0 1 2 3
# ..$ : int 4 5 6 7
# ..$ : int 8 9 10 11
# - attr(*, "drop")= logi TRUE
# - attr(*, "group_sizes")= int 4 4 4
# - attr(*, "biggest_group_size")= int 4
str(dt_ungrouped)
# Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 12 obs. of 3 variables:
# $ ID : Factor w/ 3 levels "a","b","c": 1 1 1 1 2 2 2 2 3 3 ...
# $ VAR : int 29 41 79 86 29 41 79 86 29 41 ...
# $ COUNTER: int 1 2 3 4 1 2 3 4 1 2 ...