在数据帧中创建移动时段并计算内容(R studio)

在数据帧中创建移动时段并计算内容(R studio),r,dataframe,loops,R,Dataframe,Loops,我有一个数据框,其中包含1961年1月至2017年12月期间每天的降水数据,如下所示: DF=data.frame(年、月、日、降水量值) 我希望从1961年1月1日开始创建30天的时段,因此第一个时段将是1961年1月1日至1月30日,并希望R计算无雨天数(降水量值=0)。然后,我想在第二天做同样的事情:1月2日,所以这段时间将是1月2日到1月31日,等等。在那之后,我需要R创建一个包含1961年所有结果的数据框架。因此,它应该是一个数据框,只有一列有值(这些值将是每个时段无雨的天数) 那么我

我有一个数据框,其中包含1961年1月至2017年12月期间每天的降水数据,如下所示:

DF=data.frame(年、月、日、降水量值)

我希望从1961年1月1日开始创建30天的时段,因此第一个时段将是1961年1月1日至1月30日,并希望R计算无雨天数(降水量值=0)。然后,我想在第二天做同样的事情:1月2日,所以这段时间将是1月2日到1月31日,等等。在那之后,我需要R创建一个包含1961年所有结果的数据框架。因此,它应该是一个数据框,只有一列有值(这些值将是每个时段无雨的天数)

那么我需要对所有这些年做同样的事情。这意味着我将得到56个数据帧(每年1个),之后我可以用所有数据帧制作一个矩阵(将每个数据帧作为一行)


问题是我不知道如何开始。我不知道如何做循环。我知道这应该很容易,但我做起来有困难。特别是,我不知道如何告诉R每一年停止一次,重新开始,并用值创建一个新的数据框/向量。

请提供您的数据的可复制子集,以便其他人能够更有效地帮助您。虽然我无法教您如何从头开始创建循环,但我认为这里有一些代码会有所帮助。此代码使用简单的for循环简单地计算30天移动平均降水量。您可以使用dplyr按年份过滤这些移动平均值,并创建数据帧。注意,我没有计算这里没有降水的天数,但是如果需要的话,可以很容易地修改循环

df<-data.frame(year = rep(1967:2002, each =12*30), 
               month = rep(rep(1:12, each = 30), 36), 
               day = rep(seq(1,30, by = 1), 432),
                precipitation = sample(1:2000, 12*36))
df

#create a column that goes from 1 to however long your dataframe is
df$marker <- 1:nrow(df)

#'Now we create a simple loop to calculate the mean precipitation for 
#'every 30 day window. You can modify this to count the number of days with 
#'0 precipitation


#'the new column moving precip will tell you the mean precipitation for the 
#' past 30 days relative to its postion. So if your on row 55, it will give 
#' you the mean precipitation from row 25 to 55


df$movingprecip<-NA
for(i in 1:nrow(df)){
  start = i #this says we start at i
  end = i + 30 #we end 30 days later from i
  if(end > nrow(df)){
    #here I tell R to print this if there is not enough days
    #in the dataset (30 days) to calculate the 30 day window mean
    #this happens at the beginning of the dataset because we need to get to the
    #30th row to start calculating means
    print("not able to calculate, not 30 days into the data yet") 
  }else{
    #Here I calculate the mean the of the past 30 days of precip
    df$movingprecip[end] = mean(df[start:end,4])}
}
df