我想从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
答案 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_Sex
中df1
的每个条目,我们首先找到在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