我想要的可以描述爲:給一個數據框,包含所有的病例控制對。在以下示例中,y是病例控制對的ID。我的數據集中有3對。我正在對y的不同值進行重新採樣(該對將既被選中也不被選中)。根據具有重複值的向量選擇數據幀的行
sample_df = data.frame(x=1:6, y=c(1,1,2,2,3,3))
> sample_df
x y
1 1 1
2 2 1
3 3 2
4 4 2
5 5 3
6 6 3
select_y = c(1,3,3)
select_y
> select_y
[1] 1 3 3
現在,我已經計算出的載體含有欲重新取樣,這是上述的select_y
成對。這意味着病例對照編號1將會出現在我的新樣本中,編號3也會出現在我的新樣本中,但會出現2次,因爲有兩個3.期望的輸出將爲:
x y
1 1
2 1
5 3
6 3
5 3
6 3
我找不出比寫一個for循環其他的有效方式...
解決方案: 基於@HubertL,經過一些修改,一個「矢量」的方法是這樣的:
sel_y <- as.data.frame(table(select_y))
> sel_y
select_y Freq
1 1 1
2 3 2
sub_sample_df = sample_df[sample_df$y%in%select_y,]
> sub_sample_df
x y
1 1 1
2 2 1
5 5 3
6 6 3
match_freq = sel_y[match(sub_sample_df$y, sel_y$select_y),]
> match_freq
select_y Freq
1 1 1
1.1 1 1
2 3 2
2.1 3 2
sub_sample_df$Freq = match_freq$Freq
rownames(sub_sample_df) = NULL
sub_sample_df
> sub_sample_df
x y Freq
1 1 1 1
2 2 1 1
3 5 3 2
4 6 3 2
selected_rows = rep(1:nrow(sub_sample_df), sub_sample_df$Freq)
> selected_rows
[1] 1 2 3 3 4 4
sub_sample_df[selected_rows,]
x y Freq
1 1 1 1
2 2 1 1
3 5 3 2
3.1 5 3 2
4 6 3 2
4.1 6 3 2
我不得不說這是一個更好的解決方案。這是一個很好的利用分裂。 –