add counter column by arranging two variables (dplyr)

点点圈 提交于 2021-01-27 20:53:10

问题


I've been looking for a while here and there but I couldn't find any solution for my situation. I have a data frame with IDs and VAR mixed within it. Here below I tried to reproduced a sample

require(dplyr)
seed(123)
N <- 3
T <- 4
id <- rep(letters[1:N], each = T) 
var <- rep(sample(seq(1:100),T),N) 
row <- sample(seq(1:(N*T)),replace = F)

dt <- data.frame(ID=id,VAR=var,ROW=row) %>%
  arrange(ROW) %>%
  select(-ROW)

and I'd like to arrange by ID and VAR and add a counter per group in order to get something like

   ID VAR COUNTER
1   a   1 1
2   a  11 2
3   a  22 3
4   a  64 4
5   b   1 1
6   b  11 2
7   b  22 3
8   b  64 4
9   c   1 1
10  c  11 2
11  c  22 3
12  c  64 4

all of this, if it is possible, just by using dplyr or base functions.


回答1:


Within dplyr you need to arrange() by ID and VAR and then group_by() just ID.

Then you use mutate() to add a new column, counting from 1 to n() (where n() is a dplyr function for 'number of rows')

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

A comment on ungrouping

I do this to remove all the 'grouping' attributes associated with a grouped_df. In this example the result is the same, but those grouped attributes may bite you further down the line.

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 ...


来源:https://stackoverflow.com/questions/45045180/add-counter-column-by-arranging-two-variables-dplyr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!