R:将 forecast::tsclean() 的输出按日期时间关联回原始数据帧
R: Relate output of forecast::tsclean() back to original dataframe by datetime
我正在尝试使用 forecast
包中的 tsclean()
函数从时间序列数据框中删除已建立的异常值。
为了使用 tsclean()
,我已将原始数据转换为 ts()
对象。不幸的是,这会删除我的时间戳向量,这会在以后造成一些问题。将我的 ts()
对象输入 tsclean()
函数后,将返回一个经过适当清理的时间序列。但是,我无法将此结果连接回我的原始数据框,因为 POSIXct
时间戳不再存在于我的 tsclean()
对象中。我最终尝试在我的原始数据框中针对解释变量 df$X
对已清理的响应变量 df$Y
执行 lm()
。
library(forecast)
datetime <- as.POSIXct(c("2018-03-05 15:54:00", "2018-03-05 15:55:00", "2018-03-05 15:56:00", "2018-03-05 15:57:00", "2018-03-05 15:58:00"))
Y <- c(1, 5, 9, 100, 2)
X <- c(3, 4, 2, 4, 5)
df <- data.frame(datetime, Y, X)
time_series <- ts(df$Y)
time_series_clean <- tsclean(time_series)
原始数据框:
datetime Y X
1 2018-03-05 15:54:00 1 3
2 2018-03-05 15:55:00 5 4
3 2018-03-05 15:56:00 9 2
4 2018-03-05 15:57:00 100 4
5 2018-03-05 15:58:00 2 5
想要的结果:
datetime Y X
1 2018-03-05 15:54:00 1 3
2 2018-03-05 15:55:00 5 4
3 2018-03-05 15:56:00 9 2
4 2018-03-05 15:58:00 2 5
之前tsclean()
:
tsclean()
之后:
如果我正确理解了你的问题,你想从原始数据中删除异常值。一种解决方案是使用 tsoutliers
函数:
time_series_outliers <- tsoutliers(time_series) # identify outliers
df <- df[-time_series_outliers$index, ] # remove them from the original data
这个函数也很有趣,如果你想要建议值来替换异常值,则给出 $replacements
。
我正在尝试使用 forecast
包中的 tsclean()
函数从时间序列数据框中删除已建立的异常值。
为了使用 tsclean()
,我已将原始数据转换为 ts()
对象。不幸的是,这会删除我的时间戳向量,这会在以后造成一些问题。将我的 ts()
对象输入 tsclean()
函数后,将返回一个经过适当清理的时间序列。但是,我无法将此结果连接回我的原始数据框,因为 POSIXct
时间戳不再存在于我的 tsclean()
对象中。我最终尝试在我的原始数据框中针对解释变量 df$X
对已清理的响应变量 df$Y
执行 lm()
。
library(forecast)
datetime <- as.POSIXct(c("2018-03-05 15:54:00", "2018-03-05 15:55:00", "2018-03-05 15:56:00", "2018-03-05 15:57:00", "2018-03-05 15:58:00"))
Y <- c(1, 5, 9, 100, 2)
X <- c(3, 4, 2, 4, 5)
df <- data.frame(datetime, Y, X)
time_series <- ts(df$Y)
time_series_clean <- tsclean(time_series)
原始数据框:
datetime Y X
1 2018-03-05 15:54:00 1 3
2 2018-03-05 15:55:00 5 4
3 2018-03-05 15:56:00 9 2
4 2018-03-05 15:57:00 100 4
5 2018-03-05 15:58:00 2 5
想要的结果:
datetime Y X
1 2018-03-05 15:54:00 1 3
2 2018-03-05 15:55:00 5 4
3 2018-03-05 15:56:00 9 2
4 2018-03-05 15:58:00 2 5
之前tsclean()
:
tsclean()
之后:
如果我正确理解了你的问题,你想从原始数据中删除异常值。一种解决方案是使用 tsoutliers
函数:
time_series_outliers <- tsoutliers(time_series) # identify outliers
df <- df[-time_series_outliers$index, ] # remove them from the original data
这个函数也很有趣,如果你想要建议值来替换异常值,则给出 $replacements
。