我面临的问题是,我想从基于两个类别的数据集中随机抽取150个样本"站点"one_answers";species"。因此,理想情况下,每个站点有30个样本,每个物种或多或少均匀分布。
可再生的例子:
df <- data.frame(site = rep(c("A", "B", "C", "D", "E"), each = 10), species = c("s1", rep("s2", each = 3), rep("s3", each = 16), rep("s4", each = 13), rep("s5", each = 17)), individual = c(1, 1:3, 1:16, 1:13, 1:17) )
我认为使用dplyr函数group_by(site, species)和slice_sample()是一种很好的方法,但是每组采样一定数量,而不是总共150个。我现在遇到的另一个问题是,slice_sample在每组中至少需要n个样本才能工作。这并不总是给定的。那么,是否有可能总共抽样150个,当每组没有提供所需的抽样数量时,就只抽样其他组作为补偿?
谢谢!
一种选择是nest_by(site)
,然后使用slice_sample()
从每组抽取30个样本。如果需要,我们可以用tidyr::unnest()
来得到一个"正常的";data.frame
包含所有绘制的样本。
问题可能是这样的:
每个物种或多或少均匀分布
当我们观察你的site
s时,我们可以看到大多数站点只有一个物种。因此,从原始数据中提取样本将导致只包含特定species
的特定站点。或者,我们可以对species
进行采样,并随机分配一个site
,而不考虑这个species
从未在那里被观察到。
library(dplyr)
library(tidyr)
site_sample <- df %>%
nest_by(site) %>%
summarise(data = list(slice_sample(data, n = 30, replace = TRUE)))
#> `summarise()` has grouped output by 'site'. You can override using the `.groups`
#> argument.
site_sample
#> # A tibble: 5 x 2
#> # Groups: site [5]
#> site data
#> <chr> <list>
#> 1 A <tibble [30 x 2]>
#> 2 B <tibble [30 x 2]>
#> 3 C <tibble [30 x 2]>
#> 4 D <tibble [30 x 2]>
#> 5 E <tibble [30 x 2]>
site_sample %>%
unnest(data)
#> # A tibble: 150 x 3
#> # Groups: site [5]
#> site species individual
#> <chr> <chr> <dbl>
#> 1 A s1 1
#> 2 A s3 1
#> 3 A s1 1
#> 4 A s3 5
#> 5 A s3 3
#> 6 A s3 4
#> 7 A s2 2
#> 8 A s3 3
#> 9 A s3 5
#> 10 A s3 2
#> # ... with 140 more rows
原始数据
df <- data.frame(site = rep(c("A", "B", "C", "D", "E"), each = 10), species = c("s1", rep("s2", each = 3), rep("s3", each = 16), rep("s4", each = 13), rep("s5", each = 17)), individual = c(1, 1:3, 1:16, 1:13, 1:17) )
由reprex包(v2.0.1)在2022-12-16创建