Home > Blockchain >  How to assign a "reseting" group number by the second grouping variable in R?
How to assign a "reseting" group number by the second grouping variable in R?

Time:11-05

My data looks like this:

Measurement Compound Measure
1 A 111
1 A 222
1 B 333
1 B 444
2 C 555
2 C 666
2 D 777
2 D 888

And I'm trying to assign a "reseting" group number based on Compound:

Measurement Compound Measure Compound_order
1 A 111 1
1 A 222 1
1 B 333 2
1 B 444 2
2 C 555 1
2 C 666 1
2 D 777 2
2 D 888 2

Didn't come up with the solution on dplyr group_by.

DATA

dat <- data.frame(
  Measurement = c(1, 1, 1, 1, 2, 2, 2, 2),
  Compound = c("A", "A", "B", "B", "C", "C", "D", 'D'),
  Measure = 111 * 1:8
)

CodePudding user response:

You can do the following.

library(dplyr)

dat2 <- dat %>%
  group_by(Measurement) %>%
  mutate(Compound_order = as.integer(factor(Compound,
                                            levels = unique(Compound)))) %>%
  ungroup()

dat2
# # A tibble: 8 x 4
#   Measurement Compound Measure Compound_order
#         <dbl> <chr>      <dbl>          <int>
# 1           1 A            111              1
# 2           1 A            222              1
# 3           1 B            333              2
# 4           1 B            444              2
# 5           2 C            555              1
# 6           2 C            666              1
# 7           2 D            777              2
# 8           2 D            888              2

DATA

dat <- data.frame(
  Measurement = c(1, 1, 1, 1, 2, 2, 2, 2),
  Compound = c("A", "A", "B", "B", "C", "C", "D", 'D'),
  Measure = 111 * 1:8
)

CodePudding user response:

data.tablesolution

library(data.table)
setDT(dat)[, Compound_order := rleid(Compound), by = .(Measurement)]
#    Measurement Compound Measure Compound_order
# 1:           1        A     111              1
# 2:           1        A     222              1
# 3:           1        B     333              2
# 4:           1        B     444              2
# 5:           2        C     555              1
# 6:           2        C     666              1
# 7:           2        D     777              2
# 8:           2        D     888              2

CodePudding user response:

Like this:

library(tidyverse)
dat <- data.frame(
  measument = c(1,1,2,2),
  compount = c(letters[1:4])
)

dat %>% group_by(measument) %>% 
  mutate(compount_order = 1:n())
#> # A tibble: 4 x 3
#> # Groups:   measument [2]
#>   measument compount compount_order
#>       <dbl> <chr>             <int>
#> 1         1 a                     1
#> 2         1 b                     2
#> 3         2 c                     1
#> 4         2 d                     2

Created on 2021-11-05 by the reprex package (v2.0.0)

  • Related