查找匹配的对及其ID以匹配记录

时间:2017-10-27 15:55:25

标签: r dplyr data.table tidyr

我有一个巨大的数据集,我需要根据一些标准匹配样本。例如,对于某个地点和自治市镇的每个电影明星,找到两个不是电影明星的人(随机)。电影明星为1,非电影明星为0。

location<- c('manhattan', 'manhattan' ,'manhattan', 'manhattan', 'manhattan', 'manhattan')
moviestar<- c(0,1,0,0,0,1)
id<- c(1,2,3,4,5,6)
 borough <- c('williamsburg', 'williamsburg', 'williamsburg', 'williamsburg', 'williamsburg','williamsburg')

 df<- data.frame(location,moviestar, borough, id)

我想要创建一个子集,该子集具有匹配的电影明星对与居住在同一位置和行政区的另外两个非电影明星(随机挑选)。有什么建议吗?基本上有6个人住在曼哈顿,有两颗星住在曼哈顿,我想匹配每颗星,在这种情况下,2和6是星星,那么我想在最终数据中配对如下(一些随机对):

我期待的输出是这样的,

    matcheddata
    location moviestar borough       id matchpairid
    manhattan    1    williamsburg   2  match1
    manhattan    0    williamsburg   1  match1
    manhttan     0    williamsburg   5  match1
    manhattan    1    williamsburg   6  match2
    manhattan    0    williamsburg   3  match2
    manhttan     0    williamsburg   5  match2

2 个答案:

答案 0 :(得分:1)

这应该这样做:

library(data.table)
setDT(df)[, .(moviestar.id = id[moviestar == 1],
              match.id = sample(id[moviestar == 0], 2*sum(moviestar == 1)))
          , by = .(location, borough)]
#    location      borough moviestar.id match.id
#1: manhattan williamsburg            2        3
#2: manhattan williamsburg            6        5
#3: manhattan williamsburg            2        1
#4: manhattan williamsburg            6        4

您可以按照之后的任何形式按摩它。

答案 1 :(得分:0)

这是另一种直接产生预期结果的方法,其中电影明星的每一行后面都是两排随机挑选的非电影明星:

library(data.table)
setDT(df)[, {
  n_stars <- .SD[moviestar == 1, .N]
  rbind(.SD[moviestar == 1], .SD[moviestar == 0][sample.int(.N, 2L * n_stars)])[
    , pairid := rep(1:n_stars, 3L)][order(pairid)]
}, by = .(location, borough)]
    location      borough moviestar id pairid
1: manhattan williamsburg         1  2      1
2: manhattan williamsburg         0  3      1
3: manhattan williamsburg         0  1      1
4: manhattan williamsburg         1  6      2
5: manhattan williamsburg         0  4      2
6: manhattan williamsburg         0  5      2