2

不确定标题是否清晰,但我想对数据框中的一列进行洗牌,但不是针对每一行,这很容易使用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 个。

任何提示或建议将不胜感激!

4

2 回答 2

0

一种技术是提取唯一组合,以便每个 sampleID 有一行,然后您可以打乱并将打乱的项目合并回主表。这就是它的样子

library(dplyr)
df1 %>% 
  distinct(sampleID, groupID) %>% 
  mutate(shuffle_groupID = sample(groupID)) %>% 
  inner_join(df1)
于 2022-02-22T18:15:31.703 回答
0

使用 dplyrnest_byunnest

library(dplyr)

df1 |>
    nest_by(sampleID, groupID) |>
    mutate(groupID = sample(groupID, n())) |>
    unnest(cols = c(data))


+ # A tibble: 10 x 3
# Groups:   sampleID, groupID [4]
   sampleID groupID     A
      <dbl>   <int> <dbl>
 1      386       1     1
 2      386       1     0
 3      438       1     0
 4      438       1     0
 5      438       1     0
 6      438       1     1
 7      582       2     0
 8      582       2     0
 9      597       1     1
10      597       1     0
于 2022-02-22T18:33:13.143 回答