我认为您可以使用它unique
来查找所有可能的 ID / 站点,然后从唯一和子集中进行采样。
例如,让我们创建一个数据集
# Set the RNG seed for reproducibility
set.seed(12345)
ID <- rep(100:110, c(2, 6, 3, 1, 3, 8, 9, 2, 4, 5, 6))
site <- rep(1:6, c(8, 7, 8, 11, 4, 11))
species <- sample(letters[1:5], length(ID), replace=T)
df <- data.frame(ID=ID, Site=site, Species=species)
所以, df 看起来像:
> head(df, 15)
ID Site Species
1 100 1 d
2 100 1 e
3 101 1 d
4 101 1 e
5 101 1 c
6 101 1 a
7 101 1 b
8 101 1 c
9 102 2 d
10 102 2 e
11 102 2 a
12 103 2 a
13 104 2 d
14 104 2 a
15 104 2 b
总结数据,我们有:
Site 1 -> 100, 101
Site 2 -> 102, 103, 104
Site 3 -> 105
Site 4 -> 106, 107
Site 5 -> 108
Site 6 -> 109, 110
现在,假设我想从 3 个站点中进行选择
# The number of sites we want to sample
num.sites <- 3
# Find all the sites
all.sites <- unique(df$Site)
# Pick the sites.
# You may also want to check that num.sites <= length(all.sites)
sites <- sample(all.sites, num.sites)
在这种情况下,我们选择
> sites
[1] 4 5 6
好的,现在我们找到每个站点可用的 ID
# Now find the IDs in each of those sites
# simplify=F is VERY important to ensure we get a list even if every
# site has the same number of IDs
IDs <- sapply(chosen.sites, function(s)
{
unique(df$ID[df$Site==s])
}, simplify=FALSE)
这给了我们
> IDs
[[1]]
[1] 106 107
[[2]]
[1] 108
[[3]]
[1] 109 110
现在为每个站点选择一个 ID
# NOTE: this assumes the same ID is not found in multiple sites
# but it's easy to deal with the opposite case
# Again, we return a list, because sapply does not seem
# to play well with data frames... (try it!)
res <- sapply(IDs, function(i)
{
chosen.ID <- sample(as.list(i), 1)
df[df$ID==chosen.ID,]
}, simplify=FALSE)
# Finally convert the list to a data frame
res <- do.call(rbind, res)
> res
ID Site Species
24 106 4 d
25 106 4 d
26 106 4 b
27 106 4 d
28 106 4 c
29 106 4 b
30 106 4 c
31 106 4 d
32 106 4 a
35 108 5 b
36 108 5 b
37 108 5 e
38 108 5 e
44 110 6 d
45 110 6 b
46 110 6 b
47 110 6 a
48 110 6 a
49 110 6 a
所以,一切都在一个函数中
pickSites <- function(df, num.sites)
{
all.sites <- unique(df$Site)
chosen.sites <- sample(all.sites, num.sites)
IDs <- sapply(chosen.sites, function(s)
{
unique(df$ID[df$Site==s])
}, simplify=FALSE)
res <- sapply(IDs, function(i)
{
chosen.ID <- sample(as.list(i), 1)
df[df$ID==chosen.ID,]
}, simplify=FALSE)
res <- do.call(rbind, res)
}