r语言 - 基于观测数据创建多个新的重采样系列



我有7年的温度数据分成4个季节变量(春,夏,秋,冬)每个看起来像这样(春天的例子)

Day Month Year  maxtp  Season.Year Season
 1    3   2008   13.6     2008       SP
 2    3   2008   11.3     2008       SP
 3    3   2008   5.4      2008       SP

我想根据这些观测数据创建多个新的温度序列,一次一个(使用类似的方法):根据面板数据中的索引进行块采样

使用此代码

newseries1 <- sample(Spring, size=91, replace = T, prob = NULL)

但是这个序列重复了91次,这不是我想要的。

我想从任意一个随机季节中选择一个完整的Spring块。年份(2008-2014),然后从除之前选择的年份之外的任何年份中选择一个夏季块,因此除了2008年之外的任何年份。然后替换重新采样的年份,以便下一次可以再次重新采样,只是不是连续的。

我想要一个季节。年自春变,随之而来的是不同的季节。对于夏季变量是年份,然后是秋季变量,然后是冬季变量,并继续这样做,直到重新采样的长度与观察到的长度相同(在这种情况下为7年)。

总的来说,我想:

  1. 选择一个关于年序列的"块"(从一个随机的季节。年)并开始一个新的序列,然后替换它,以便再次采样。
  2. 以非连续年份的夏季跟随春季,并将其替换。
  3. 继续,直到重新采样的序列与观察到的长度相同。
  4. 重复此过程,直到有100个重新采样的系列

For newseries1 try instead

ndays <- length(Spring[, 1])
#select rows of Spring randomly (are you sure you want replace = T?)
newseries1 <- Spring[sample(1:ndays, size = ndays, replace = T, prob = NULL),]

依次选择各季节的年份数据:

y.lst <- 2008:2014
nssn <- 7*100*4 #desired number of annual cycles times four seasons
y <- rep(NA, nssn) #initialise: vector of selected years
#first spring
y[1] <- sample(y.lst, 1)
#subsequent seasons
for(s in 2:nssn){
  #selects a year from a sublist of years which excludes that of the previous season
  y[s] <- sample(y.lst[y.lst != y[s - 1]], 1)
}

然后编译数据帧(假设原始数据在数据帧data中):

#first Spring
Ssn <- data[with(data, Year == y[1] & Season == "SP"),]
ndays <- length(Spring[, 1])
newseries1 <- Ssn[sample(1:ndays, size = ndays, replace = T, prob = NULL),]
#initialise data frame
data2 <- Ssn
#subsequent seasons
for(s in 2:nssn){
  Ssn <- data[with(data, Year == y[s] & Season == "..."),]
  ndays <- length(Spring[, 1])
  newseries1 <- Ssn[sample(1:ndays, size = ndays, replace = T, prob = NULL),]
  data2 <- rbind(data2, Ssn)
}

您需要创建一个要选择的季节标签向量。使用%%余数函数在每种情况下选择合适的季节标签(即s%%4为2表示"SU")