R 随机选择具有约束的行

R 随机选择具有约束的行,r,data-analysis,R,Data Analysis,我想要一个3-4组不同的5行,每行应该来自不同的cluster2列。我们如何在R中做到这一点?这里有一个解决方案: 数据: 您可以将这些示例存储在不同的数据帧中,并将其捕获到列表中: df1 <- df %>% group_by(col2) %>% sample_n(1) df2 <- df %>% group_by(col2) %>% sample_n(1) df3 <- df %>% group_by(col2) %>% sample_n

我想要一个3-4组不同的5行,每行应该来自不同的cluster2列。我们如何在R中做到这一点?

这里有一个解决方案:

数据:

您可以将这些示例存储在不同的数据帧中,并将其捕获到列表中:

df1 <- df %>% group_by(col2) %>% sample_n(1)
df2 <- df %>% group_by(col2) %>% sample_n(1)
df3 <- df %>% group_by(col2) %>% sample_n(1)

df_list <- list(df1, df2, df3)
df_list
[[1]]
# A tibble: 5 x 3
# Groups:   col2 [5]
   col1  col2  col3
  <int> <int> <int>
1   118     1   146
2   117     2   163
3   112     3   167
4   102     4   161
5   108     5   158

[[2]]
# A tibble: 5 x 3
# Groups:   col2 [5]
   col1  col2  col3
  <int> <int> <int>
1   106     1   161
2   117     2   163
3   110     3   144
4   102     4   161
5   104     5   170

[[3]]
# A tibble: 5 x 3
# Groups:   col2 [5]
   col1  col2  col3
  <int> <int> <int>
1   106     1   161
2   119     2   149
3   109     3   148
4   113     4   161
5   104     5   170
您可以使用expand.grid获取每个组的所有可能组合,如:

expand.grid(split(seq_len(nrow(x)), x$cl))[1:4,]
#  1 2 3 4 5
#1 1 5 8 6 4
#2 2 5 8 6 4
#3 3 5 8 6 4
#4 1 9 8 6 4
数据:


我想你可以试试下面的代码

res <- split(df,with(df,ave(grp,grp,FUN = function(x) sample(seq_along(x)))))
资料


请澄清第二栏的意思,并提供一些可重复的数据!欢迎来到SO。这是一篇很好的第一篇文章,但下次请不要将数据作为图像共享,而是使用dput等函数将代码直接复制到文章中。
expand.grid(split(seq_len(nrow(x)), x$cl))[1:4,]
#  1 2 3 4 5
#1 1 5 8 6 4
#2 2 5 8 6 4
#3 3 5 8 6 4
#4 1 9 8 6 4
x <- data.frame(cl = c(1,1,1,5,2,4,5,3,2,4,3,3))
res <- split(df,with(df,ave(grp,grp,FUN = function(x) sample(seq_along(x)))))
> res
$`1`
    id grp
3  103   1
5  105   2
6  106   4
7  107   5
12 112   3

$`2`
    id grp
2  102   1
4  104   5
9  109   2
10 110   4
11 111   3

$`3`
   id grp
1 101   1
8 108   3
df <- structure(list(id = c(101, 102, 103, 104, 105, 106, 107, 108, 
109, 110, 111, 112), grp = c(1, 1, 1, 5, 2, 4, 5, 3, 2, 4, 3, 
3)), class = "data.frame", row.names = c(NA, -12L))

> df
    id grp
1  101   1
2  102   1
3  103   1
4  104   5
5  105   2
6  106   4
7  107   5
8  108   3
9  109   2
10 110   4
11 111   3
12 112   3