【发布时间】:2021-03-25 14:22:16
【问题描述】:
我是 R 新手,并试图利用一个相当简单的任务。我有一个由 20 个 obs 和 19 个变量组成的数据集,我想生成三个不重叠的 5 个 obs 组。我正在使用 dplyr 包中的 slice_sample 函数,但我如何重申排除已在第一轮中获得的 obs?
图书馆(“dplyr”) set.seed(123)
NF_1
【问题讨论】:
-
请编辑您的问题以包含
dput(NF)
我是 R 新手,并试图利用一个相当简单的任务。我有一个由 20 个 obs 和 19 个变量组成的数据集,我想生成三个不重叠的 5 个 obs 组。我正在使用 dplyr 包中的 slice_sample 函数,但我如何重申排除已在第一轮中获得的 obs?
图书馆(“dplyr”) set.seed(123)
NF_1
【问题讨论】:
dput(NF)
您可以使用基础 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(这是一个将函数“应用”到集合的函数值)。 “lapply”中的“l”表示它返回一个列表。还有其他类型的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
【讨论】:
lapply 会为每次迭代返回一个列表。您可以循环n_groups 次并每次生成一个 size = 5 的样本。然后根据需要标记样本。如果您需要我更新答案,请告诉我。