不确定标题是否清晰,但我想对数据框中的一列进行洗牌,但不是针对每一行,这很容易使用sample()
,而是针对来自同一样本的成对观察。
例如,我有以下数据框 df1:
>df1
sampleID groupID A B C D E F
438 1 1 0 0 0 0 0
438 1 0 0 0 0 1 1
386 1 1 1 1 0 0 0
386 1 0 0 0 1 0 0
438 2 1 0 0 0 1 1
438 2 0 1 1 0 0 0
582 2 0 0 0 0 0 0
582 2 1 0 0 0 1 0
597 1 0 1 0 0 0 1
597 1 0 0 0 0 0 0
我想在这里为每个样本的 groupID 随机打乱标签,而不是观察,因此结果如下所示:
>df2
sampleID groupID A B C D E F
438 1 1 0 0 0 0 0
438 1 0 0 0 0 1 1
386 2 1 1 1 0 0 0
386 2 0 0 0 1 0 0
438 1 1 0 0 0 1 1
438 1 0 1 1 0 0 0
582 1 0 0 0 0 0 0
582 1 1 0 0 0 1 0
597 2 0 1 0 0 0 1
597 2 0 0 0 0 0 0
请注意,在第 2 列(groupID)中,样本 386 现在是 2(对于两个观察值)。
我已经四处搜索,但没有找到任何可以按我想要的方式工作的东西。我现在所拥有的只是洗牌第二列。我尝试按如下方式使用 dplyr:
df2 <- df1 %>%
group_by(sampleID) %>%
mutate(groupID = sample(df1$groupID, size=2))
但当然,这只需要所有组 ID 并随机选择 2 个。
任何提示或建议将不胜感激!