我有一个名为 daily 的数据框,如下所示:
daily[1:10,]
Climate_Division Date Precipitation
1 1 1948-07-01 0.2100000
2 1 1948-07-02 0.7000000
3 1 1948-07-03 0.1900000
4 1 1948-07-04 0.1033333
5 1 1948-07-05 0.1982895
6 1 1948-07-06 0.1433333
7 1 1948-07-07 NA
8 1 1948-07-08 NA
9 1 1948-07-09 NA
10 1 1948-07-10 NA
我想要实现的目标是平均所有年份(1948-1995)的所有日期值,以替换该特定日期发生的 NA 值。例如,由于第 7 行的 NA 为 1948 年 7 月 7 日,我将对 1948 年至 1995 年的所有 7 月 7 日进行平均,并将该特定日期替换为平均值。
到目前为止,我尝试过的是:
index <- which(is.na(daily$Precipitation)) # find where the NA's occur
daily_avg <- daily # copy dataframe
daily_avg$Date <- strftime(daily_avg$Date, format="2000-%m-%d") # Change the Date format to represent only the day and month and disregard year
daily_avg <- aggregate(Precipitation~Date, FUN = mean, data = daily_avg, na.rm = TRUE) # find the mean precip per day
daily[index,3] <- daily_avg[daily_avg$Date %in% strftime(daily[index,2], format="2000-%m-%d"), 2]
代码中的最后一行无法正常工作,我不知道为什么。这就是我对这个问题的思考过程。但是,我想知道是否有更好的方法来使用我不知道的内置函数。任何帮助是极大的赞赏。谢谢