![](/img/trans.png)
[英]Calculate n-dimensional euclidean distance from group centroids for each sample and select the lowest 3 for each group in R
[英]Randomly select sample from each group using weight
我知道dplyr
中有sample_n
函數,但不知道如何選擇帶有權重的樣本。
例如;
iris %>%
group_by(Species) %>%
sample_n(size = 3)
這帶來了每組 30 個觀察值。
但我想總共進行 30 次觀察,並希望這 30 個樣本成為第 1 組的 %70、第 2 組的 %20 和第 3 組的 %10,例如
提前致謝。
借用 KoenV 在評論中發布的鏈接:
library(dplyr)
library(purrr)
sample_size <- 30
groups <- c(0.7, 0.1, 0.2)
group_size <- sample_size * groups
iris %>%
group_split(Species)%>%
map2_dfr(group_size, ~ slice_sample(.x, n = .y))
# A tibble: 30 × 5
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fct>
1 4.8 3.1 1.6 0.2 setosa
2 4.8 3.4 1.6 0.2 setosa
3 5.1 3.4 1.5 0.2 setosa
4 4.4 3 1.3 0.2 setosa
5 4.6 3.4 1.4 0.3 setosa
6 5.5 4.2 1.4 0.2 setosa
7 5.5 3.5 1.3 0.2 setosa
8 4.9 3 1.4 0.2 setosa
9 5.1 3.8 1.9 0.4 setosa
10 5.7 4.4 1.5 0.4 setosa
# A tibble: 3 × 2
Species n
<fct> <int>
1 setosa 21
2 versicolor 3
3 virginica 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.