Voici comment je traite cela, mais je ne suis pas familier avec ts
et je suis sûr qu'il ya une meilleure option. Pour récupérer la date à partir de la position max/min, vous pouvez indexer l'objet créé par time
sur votre ts
. Par exemple: time(data)[which.max(data)]
; Idem pour which.min
.
ensuite pour convertir cela en une année appropriée (facile) et mois (difficile) index, je crée habituellement cette fonction:
numyear2monthyear <- function(x){
c(trunc(x), # entire part = year
round((x-floor(x))*12 + 1)) # decimal part * 12 + 1 (Jan=0) = Month
}
est un exemple:
set.seed(123) # for the sake of reproducibility
data <- ts(round(rnorm(60), 2), frequency = 12, end = c(2016, 12))
data
Jan Feb Mar Apr May Jun Jul Aug
2012 -0.56 -0.23 1.56 0.07 0.13 1.72 0.46 -1.27
2013 0.40 0.11 -0.56 1.79 0.50 -1.97 0.70 -0.47
2014 -0.63 -1.69 0.84 0.15 -1.14 1.25 0.43 -0.30
2015 0.55 -0.06 -0.31 -0.38 -0.69 -0.21 -1.27 2.17
2016 0.78 -0.08 0.25 -0.03 -0.04 1.37 -0.23 1.52
Sep Oct Nov Dec
2012 -0.69 -0.45 1.22 0.36
2013 -1.07 -0.22 -1.03 -0.73
2014 0.90 0.88 0.82 0.69
2015 1.21 -1.12 -0.40 -0.47
2016 -1.55 0.58 0.12 0.22
which.min(data)
[1] 18
which.max(data)
[1] 44
numyear2monthyear(time(data)[which.max(data)])
[1] 2015 8
numyear2monthyear(time(data)[which.min(data)])
[1] 2013 6
Et généralement, je transformer cela en une autre fonction pratique, comme:
extrema_dates <- function(ts){
ts_min_date <- numyear2monthyear(time(ts)[which.min(ts)])
ts_max_date <- numyear2monthyear(time(ts)[which.max(ts)])
list(min=min(ts),
min_year=ts_min_date[1],
min_month=ts_min_date[2],
max=max(ts),
max_year=ts_max_date[1],
max_month=ts_max_date[2])
}
> extrema_dates(data)
$min
[1] -1.97
$min_year
[1] 2013
$min_month
[1] 6
$max
[1] 2.17
$max_year
[1] 2015
$max_month
[1] 8
J'espère que cela résout votre problème (et serait hap py pour voir une meilleure option pour le faire).
Peut-être que 'lubridate :: date_decimal (temps (données) [which.min (données)], tz = "UTC") ' –
' as.Date.yearmon (heure (données) [which.max (données)]) ' –