R 中数据 frame/tibble 中的样本分组行

Sample grouped rows from a data frame/tibble in R

我有如下数据集

df = data.frame("Country" = rep(sample(c("USA", "Germany", "Japan", "Slovakia", "Togo")),2))
df$Value = sample(c(1:1000), 10) 

现在我想从那个 df 中随机抽样,比方说,3 个国家。这意味着我想要所有 6 行都属于 3 个国家。因此,每次我决定从一个可变国家/地区进行抽样时,我总是会得到与该国家/地区相关的所有(此处为两行)行。

我该怎么做,下面的代码不是一直有效,有时只返回 2 个国家

df %>% filter(Country %in% sample(Country, 3))

谢谢!

我们可以用 unique 换行以从 'Country' 中删除重复项并在 sample 中使用它来确保总是有 3 sample 'Country'

library(dplyr)
df %>% 
   filter(Country %in% sample(unique(Country), 3))