R 随机抽样
我是新手,尝试利用一个相当简单的任务。我有一个由19个变量的20个OB组成的数据集,我想生成3个5个OB的非重叠组。我使用的是dplyr包中的slice_sample函数,但是如何排除第一轮中已经获取的obs呢 图书馆(“dplyr”) 种子集(123)R 随机抽样,r,grouping,sampling,R,Grouping,Sampling,我是新手,尝试利用一个相当简单的任务。我有一个由19个变量的20个OB组成的数据集,我想生成3个5个OB的非重叠组。我使用的是dplyr包中的slice_sample函数,但是如何排除第一轮中已经获取的obs呢 图书馆(“dplyr”) 种子集(123) NF_1您可以使用base R中的sample函数 您所要做的就是使用replace=FALSE对行进行采样,这意味着您将不会有任何重叠。您还可以定义样本数 n_groups <- 3 observations_per_group <
NF_1您可以使用base 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, ]
好的,我现在如何从NF_1获得5个不同的数据帧?我可以为使用sample函数生成的组添加一个名称或编号吗?当然,您可以使用循环结构。使用
lappy
返回每次迭代的列表。您可以循环n_组
次,每次生成一个大小为5的样本。然后,根据您的需要给样品贴上标签。如果您需要我更新答案,请告诉我。是的,因为我以前从未使用过Lappy函数,我尝试过,但语法失败……对不起,我是一个非常非常初级的水平……我已经相应地编辑了我的答案。我强烈建议您看一看,了解更多关于R语言的知识!另外,如果我的回答对你有帮助,请投票并接受它。如果您需要更多帮助,请告诉我。请编辑您的问题以包括dput(NF)
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