首页 > 解决方案 > 从不是 R 中先前样本子集的数据帧中采样随机行

问题描述

新手来了 我的问题有两个步骤。我想从一个数据框中采样多行(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 循环在大型数据集上运行它,以便它为每次迭代运行代码但每次循环运行时选择不同的组,这可能吗?

标签: rdataframesubsetsample

解决方案


鉴于我们所知道的,@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

但是,如果由于某种原因您的采样需要其他东西,那么您可以将第二次采样限制为第一次采样中未包含的采样。一个好方法是,如果您在每一行中都有某种形式的唯一 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

推荐阅读