Special group number for each data combination

I would like to assign a different group number for each pair of lines. and for some pairs, unique numbers are assigned in the form of a group number.

change

We can think that they exist in data as pairs. If these pairs exist on strings, assign them a group number up to the next pairs. Since there may be other rows of data in real data.

Here is sample data

 names <- c(c("bad","good"),c("good","bad"),c("bad","J.James"),c("Good","J.James"),c("J.James","Good"),c('Veni',"vidi","Vici"))

  df <- data.frame(names)

      names
1      bad
2     good
3     good
4      bad
5      bad
6  J.James
7     Good
8  J.James
9  J.James
10    Good
11    Veni
12    vidi
13    Vici

since I concentrated each pair, such as c ("bad", "good"), I would like to group them and c('Veni',"vidi","Vici")assign a unique number to the pairs 666.

Thus, the expected output

     names Group
1      bad     1
2     good     1
3     good     2
4      bad     2
5      bad     3
6  J.James     3
7     Good     4
8  J.James     4
9  J.James     5
10    Good     5
11    Veni     666
12    vidi     666
13    Vici     666

I would be grateful for your help in this.

I also posted a more complex case as a new question at the suggestion of commentators.

+2
1

- :

x <- c('Veni',"vidi","Vici")
library(data.table)
setDT(df)[, Group := ((sequence(nrow(df))-1) %/% 2)+1][names %in% x, Group := 666][]
#       names Group
#  1:     bad     1
#  2:    good     1
#  3:    good     2
#  4:     bad     2
#  5:     bad     3
#  6: J.James     3
#  7:    Good     4
#  8: J.James     4
#  9: J.James     5
# 10:    Good     5
# 11:    Veni   666
# 12:    vidi   666
# 13:    Vici   666
+4

Source: https://habr.com/ru/post/1693952/


All Articles