每种数据组合的特殊组号 [英] Special group number for each combination of data

查看:108
本文介绍了每种数据组合的特殊组号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为每对行分配不同的组号。

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

编辑

我们可以认为那些在数据中成对存在。如果行中存在这些对,请为它们分配一个组号,直到下一对。由于实际数据中可能还有其他数据行。

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.

以下是示例数据

 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

当我集中每对时,例如c( bad, good)希望将它们分组并为 c('Veni', vidi, Vici)对分配唯一编号 666

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.

因此,预期输出

     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've also posted a more complicated case as a new question at the suggestion of commenters.

推荐答案

您可以尝试以下操作:

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

这篇关于每种数据组合的特殊组号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆