来自数据帧的随机行不是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