用移动平均值替换时间序列数据中的异常值。

huangapple go评论61阅读模式
英文:

Replacing unusual values in timeseries data with moving average values

问题

我想要将异常降雨替换为合理的数值。

我希望使用2-3周的降雨移动平均来替代它们。

library(tidyverse)
library(lubridate)

week <- c("10-03-2021", "10-10-2021", "10-17-2021", "10-24-2021", "10-31-2021", "11-6-2021", "11-13-2021", "11-20-2021", "11-27-2021")
rainfall <- c(11, 12, 13, 1010, 1000, 16, 16, 18, 15)

tbl <- tibble(week = mdy(week), 
              rainfall = rainfall)

如果您需要进一步的翻译或解释,请告诉我。

英文:

I would like to replace unusual rainfall with reasonable values.

I wish to use moving average of 2-3 week's of rainfall to replace them.

library(tidyverse)
library(lubridate)

week <- c("10-03-2021", "10-10-2021", "10-17-2021", "10-24-2021", "10-31-2021", "11-6-2021", "11-13-2021", "11-20-2021", "11-27-2021")
rainfall <- c(11, 12, 13, 1010, 1000, 16, 16, 18, 15)

tbl <- tibble(week = mdy(week), 
              rainfall = rainfall)

答案1

得分: 1

You can use dplyr in combination with the zoo package.

使用 `dplyr` 与 `zoo` 包结合。
library(dplyr)
library(zoo)
tbl <- tbl %>% mutate(rainfall.MA = rollmean(rainfall, 3, fill = NA, align = 'right'))

If you only wish to replace the high values (say, 1000 or more):

如果您只想替换高值(例如,1000或更多):
highvalues <- which(tbl$rainfall >= 1000 )
tbl$rainfall[ highvalues ] <- tbl$rainfall.MA[ highvalues ]

If your aim is to deal with outliers, you might look into logarithmic transformation, such as

如果您的目标是处理异常值,您可以考虑对数变换,例如:
tbl$ln_rainfall <- log(tbl$rainfall)
英文:

You can use dplyr in combination with the zoo package.

library(dplyr)
library(zoo)
tbl &lt;- tbl %&gt;% mutate(rainfall.MA = rollmean(rainfall, 3, fill = NA, align = &#39;right&#39;))

If you only wish to replace the high values (say, 1000 or more):

highvalues &lt;- which(tbl$rainfall &gt;= 1000 )
tbl$rainfall[ highvalues ] &lt;- tbl$rainfall.MA[ highvalues ]

If your aim is to deal with outliers, you might look into logaritmic transformation, such as

tbl$ln_rainfall &lt;- log(tbl$rainfall)

huangapple
  • 本文由 发表于 2023年6月30日 05:22:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76584676.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定