首页 > 解决方案 > 随机抽样 R

问题描述

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

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

NF_1 <- slice_sample(NF, n = 5)

标签: rgroupingsampling

解决方案


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

您所要做的就是使用 对行进行采样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(这是一个将函数“应用”到一组值的函数)。“lapply”中的“l”表示它返回一个列表。还有其他类型的apply功能。您可以在此处阅读更多相关信息(我强烈建议您这样做!)。

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

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


推荐阅读