我有一个名为日常数据框,看起来像这样:平均多年来每日数据中的R替换NA值
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排在1948年7月7日有一个NA,所以我将在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]
在最后一行代码不能正常工作,我不知道为什么还没有。这就是我对这个问题的思考过程。但是,我想知道是否有更好的方式使用我不知道的内置函数来完成它。任何帮助是极大的赞赏。谢谢
+ 1(...,格式= '%间%d') ' – mnel 2013-03-20 05:15:09
@agstudy,我对没有给出一个好例子表示歉意。你的方法完美无缺!谢谢 – 2013-03-20 06:05:07