Special group number for each combination of data

2019-07-11 13:55发布

I would like to assign different group number for each pairs of rows. and for some pairs assigning unique numbers as a group number.

edit

We can think of those are exist in the data as pairs. If those pairs exist in the rows, assign a group number to them until the next pairs. Since there might be other data rows in the real data.

Here is the example 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

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

So 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 appreciate your help on this.

I've also posted a more complicated case as a new question at the suggestion of commenters.

1条回答
虎瘦雄心在
2楼-- · 2019-07-11 14:41

You can try something like the following:

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
查看更多
登录 后发表回答