选择匹配字符串的随机行

时间:2019-01-04 09:09:01

标签: r

我想从df2中随机选择与Birth_Sex相匹配的行。所选的行数应等于df1中的行数(在此示例中为2)。

df1

  Birth_Sex
  1999_1
  1969_1

df2

 ID          Birth_Sex
 123113      1999_1
 123123      1992_0
 123233      1959_0
 124513      1969_1
 124993      1969_1
 124545      1969_1

示例输出

 ID          Birth_Sex
 124545      1969_1
 123113      1999_1

3 个答案:

答案 0 :(得分:3)

使用dplyr

library(dplyr)
 df2 %>% 
   inner_join(df1) %>% 
   group_by(Birth_Sex) %>% 
   sample_n(1)
Joining, by = "Birth_Sex"
# A tibble: 2 x 2
# Groups:   Birth_Sex [2]
      ID Birth_Sex
   <int> <chr>    
1 124993 1969_1   
2 123113 1999_1  

答案 1 :(得分:2)

对于Birth_Sexdf1的每个条目,我们首先找到在df2中具有该条目的行号,并选择任一行的索引作为子集df2。 / p>

df2[sapply(df1$Birth_Sex, function(x) {
      inds = which(df2$Birth_Sex %in% x)
     if(length(inds) > 1) sample(inds, 1) else inds
}), ]


#      ID Birth_Sex
#1 123113    1999_1
#4 124513    1969_1

答案 2 :(得分:2)

这也是data.table解决方案

library(data.table)

setDT(df1)[setDT(df2), nomatch = 0L,on = 'Birth_Sex'][, .SD[sample(.N, 1)], by = Birth_Sex]

#   Birth_Sex     ID
#1:    1969_1 124513
#2:    1999_1 123113