n
我需要编写一个函数,涉及通过变量bin对 df 进行子集。就像,如果n
是 2,则在两个 bin 中对 df 进行多次二次采样(从前半部分开始,然后从后半部分开始)。如果n
为 3,则在 3 个 bin(第一个 1/3、第二个 1/3、第三个 1/3)中进行子采样。到目前为止,我一直在手动为不同长度的 n 执行此操作,并且我知道必须有更好的方法来执行此操作。我想把它写成一个n
作为输入的函数,但到目前为止我还不能让它工作。代码如下。
# create df
df <- data.frame(year = c(1:46),
sample = seq(from=10,to=30,length.out = 46) + rnorm(46,mean=0,sd=2) )
# real df has some NAs, so we'll add some here
df[c(20,32),2] <- NA
这个df是46年的采样。我想假装不是 46 个样本,我只取了 2 个,但在上半年(1:23)随机一年,在下半年(24:46)随机一年。
# to subset in 2 groups, say, 200 times
# I'll make a df of elements to sample
samplelist <- data.frame(firstsample = sample(1:(nrow(df)/2),200,replace = T), # first sample in first half of vector
secondsample = sample((nrow(df)/2):nrow(df),200, replace = T) )# second sample in second half of vector
samplelist <- as.matrix(samplelist)
# start a df to add to
plot_df <- df %>% mutate(first='all',
second = 'all',
group='full')
# fill the df using coords from expand.grid
for(i in 1:nrow(samplelist)){
plot_df <<- rbind(plot_df,
df[samplelist[i,] , ] %>%
mutate(
first = samplelist[i,1],
second = samplelist[i,2],
group = i
))
print(i)
}
(如果我们可以让它跳过“NA”样本年份的样本,那就太好了)。
所以,如果我想为三点而不是两点执行此操作,我会重复这样的过程:
# to subset in 3 groups 200 times
# I'll make a df of elements to sample
samplelist <- data.frame(firstsample = sample(1:(nrow(df)/3),200,replace = T), # first sample in first 1/3
secondsample = sample(round(nrow(df)/3):round(nrow(df)*(2/3)),200, replace = T), # second sample in second 1/3
thirdsample = sample(round(nrow(df)*(2/3)):nrow(df), 200, replace=T) # third sample in last 1/3
)
samplelist <- as.matrix(samplelist)
# start a df to add to
plot_df <- df %>% mutate(first='all',
second = 'all',
third = 'all',
group='full')
# fill the df using coords from expand.grid
for(i in 1:nrow(samplelist)){
plot_df <<- rbind(plot_df,
df[samplelist[i,] , ] %>%
mutate(
first = samplelist[i,1],
second = samplelist[i,2],
third = samplelist[i,3],
group = i
))
print(i)
}
但是,我想这样做很多次,最多采样 20 次(所以在 20 个 bin 中),所以这种手动方法是不可持续的。你能帮我写一个函数说“从n个箱子中挑选一个样本x次”吗?
顺便说一句,这是我用完整的df制作的情节:
plot_df %>%
ggplot(aes(x=year,y=sample)) +
geom_point(color="grey40") +
stat_smooth(geom="line",
method = "lm",
alpha=.3,
aes(color=group,
group=group),
se=F,
show.legend = F) +
geom_line(color="grey40") +
geom_smooth(data = plot_df %>% filter(group %in% c("full")),
method = "lm",
alpha=.7,
color="black",
size=2,
#se=F,
# fill="grey40
show.legend = F
) +
theme_classic()