2017-04-17 69 views
0

我想创建条件随机对而不使用for-loops,因此我可以使用大数据集的代码。起初,我创建一个唯一的ID行和随机指定两个不同的“类型”我行:矢量化条件随机匹配

df<-data.frame(id=1:10,type=NA,partner=NA) 
df[sample(df$id,nrow(df)/2),"type"]<-1 ##random 50% type 1 
df[which(is.na(df$type)==TRUE),"type"]<-2 ##other 50% type 2 
df 
    id type partner 
1 1 2  NA 
2 2 1  NA 
3 3 1  NA 
4 4 1  NA 
5 5 2  NA 
6 6 1  NA 
7 7 1  NA 
8 8 2  NA 
9 9 2  NA 
10 10 2  NA 

现在我想他们接受相反类型的随机伙伴。所以我随机我的类型1 ID和匹配他们到一些类型2 ID像这样:

df$partner[which(df$type==2)]<-sample(df$id[which(df$type==1)], 
              nrow(df)/2) 

df 
    id type partner 
1 1 2  4 
2 2 1  NA 
3 3 1  NA 
4 4 1  NA 
5 5 2  2 
6 6 1  NA 
7 7 1  NA 
8 8 2  6 
9 9 2  3 
10 10 2  7 

而这就是我卡住的地方。由于某种原因,我想不出一种矢量化的方式来告诉R“取1型ID,看看这些ID在df$partner中的位置,并返回对应的行ID为df$partner,而不是NA”。一个for循环的条件随机配对

一个例子可以在这里找到:click

我敢肯定,这是很基本的,可行的,但是,任何帮助表示赞赏!

回答

1

大概,您希望匹配的类型1和类型2在对应的合作伙伴条目中具有对方的ID。完全矢量化解决方案。

# Define number of ids 
n = 100 

# Generate startingn data frame 
df = data.frame(id = 1:n, type = NA, partner = NA) 

# Generate the type column 
df$type[(a<-sample(df$id, n/2))] = 1 
df$type[(b<-setdiff(1:100, a))] = 2 

# Select a random partner id from the other type 
df$partner[a] = sample(df$id[b]) 
# Fill in partner values based on previous line 
df$partner[b] = df$id[match(df$id[b], df$partner)] 

输出:

id type partner 
    1 2  11 
    2 1  13 
    3 2  19 
    4 2  10 
    5 1  17 
    6 2  28 
    7 2  27 
    8 2  21 
    9 1  22 
10 1  4 
11 1  1 
12 2  20 
13 2  2 
14 2  25 
15 2  24 
16 2  30 
17 2  5 
18 2  29 
19 1  3 
20 1  12 
21 1  8 
22 2  9 
23 2  26 
24 1  15 
25 1  14 
26 1  23 
27 1  7 
28 1  6 
29 1  18 
30 1  16