随机抽样

Random sampling R

我是 R 的新手,正在尝试利用一个相当简单的任务。我有一个由 20 个 obs 和 19 个变量组成的数据集,我想生成三个不重叠的 5 个 obs 组。我正在使用 dplyr 包中的 slice_sample 函数,但我如何重申排除第一轮已经拾取的 obs?

图书馆(“dplyr”) set.seed(123)

NF_1 <- slice_sample(NF, n = 5)

您可以使用基础 R 中的 sample 函数。

您所要做的就是使用 replace = FALSE 对行进行采样,这意味着您不会有任何重叠。您还可以定义样本数。

n_groups <- 3
observations_per_group <- 5
size <- n_groups * obersavations_per_group
selected_samples <- sample(seq_len(nrow(NF)), size = size, replace = FALSE)

# Now index those selected rows
NF_1 <- NF[selected_samples, ]

现在,根据你的评论,如果你想生成 N 个数据帧,每个数据帧都有一些样本并相应地标记它们,你可以使用 lapply(这是一个“应用”a 的函数一组值的函数)。 “lapply”中的“l”表示它是returns一个列表。还有其他类型的 apply 函数。您可以阅读更多相关内容(我强烈建议您这样做!)here.

这段代码应该可以解决您的问题,或者至少给您一个好主意或去哪里。

n_groups <- 3
observations_per_group <- 5
size <- observations_per_group * n_groups

# First we'll get the row samples.
selected_samples <- sample(
    seq_len(nrow(NF)),
    size = size,
    replace = FALSE
)

# Now we split them between the number of groups
split_samples <- split(
    selected_samples,
    rep(1:n_groups, observations_per_group)
)

# For each group (1 to n_groups) we'll define a dataframe with samples
# and store them sequentially in a list.

my_dataframes <- lapply(1:n_groups, function(x) {
    # our subset df will be the original df with the list of samples
    # for group at position "x" (1, 2, 3.., n_groups)
    subset_df <- NF[split_samples[x], ]
    return(subset_df)
})

# now, if you need to access the results, you can simply do:
first_df <- my_dataframes[[1]] # use double brackets to access list elements