从数据框中抽取随机行,该行不是 R 中先前样本的子集

Sample random row from data frame that isn't subset of previous sample in R

这里是新手。我的问题有 2 个步骤。我想从数据框中抽取多行 (3),然后取不在第一个样本中的第二个样本(1 行)。

#here is my data frame
df = data.frame(matrix(rnorm(20), nrow=10))

#here is my first sample with 3 rows
sample_1<- df[sample(nrow(df), 3), ]


#here is my second sample
sample_2 <- df[sample(nrow(df), 1), ]

我希望第二个样本不属于第一个样本。

感谢您的帮助。谢谢!

您好!再次感谢对此的回应。我对此有一个后续问题。如果我需要在大型数据集上 运行 使用 FOR 循环,以便它 运行 每次迭代的代码但每次循环 运行 时选择不同的组,那会吗可能吗?

@GregorThomas 的建议可能是最好的,鉴于我们所知道的:采样四行,然后取一行作为您的 sample_2,其余的在 sample_1.

set.seed(42)
df <- data.frame(matrix(rnorm(20), nrow=10))
( samples <- sample(nrow(df), size = 4) )
# [1] 6 8 4 9
sample_1 <- df[ samples[-1], ]
sample_2 <- df[ samples[1],,drop = FALSE ]
sample_1
#            X1         X2
# 8 -0.09465904 -2.6564554
# 4  0.63286260 -0.2787888
# 9  2.01842371 -2.4404669
sample_2
#           X1        X2
# 6 -0.1061245 0.6359504

但是,如果出于某种原因您的抽样需要某些东西 else,那么您可以将第二次抽样限制为第一次抽样中未包含的那些。一个好方法是,如果您在每一行中都有某种形式的唯一 ID:

df$id <- seq_len(nrow(df))
df
#             X1         X2 id
# 1   1.37095845  1.3048697  1
# 2  -0.56469817  2.2866454  2
# 3   0.36312841 -1.3888607  3
# 4   0.63286260 -0.2787888  4
# 5   0.40426832 -0.1333213  5
# 6  -0.10612452  0.6359504  6
# 7   1.51152200 -0.2842529  7
# 8  -0.09465904 -2.6564554  8
# 9   2.01842371 -2.4404669  9
# 10 -0.06271410  1.3201133 10

sample_1 <- df[sample(nrow(df), 3), ]
sample_1
#           X1         X2 id
# 6 -0.1061245  0.6359504  6
# 2 -0.5646982  2.2866454  2
# 5  0.4042683 -0.1333213  5
subdf <- df[ !df$id %in% sample_1$id, ]
sample_2 <- subdf[sample(nrow(subdf), 1), ]
sample_2
#         X1         X2 id
# 7 1.511522 -0.2842529  7