Этот вопрос касается функции generate_msts() в пакете GRATIS.
Я добавляю кое-что новое (делаю, чтобы у функции были опции для преобразования ее вывода в прекрасный формат tribble или сохранение исходного формата «список») и готовлю обновление для CRAN.
Добавьте новый код, как показано ниже (детали кодов с примером показаны внизу вопроса)
Интересно, должен ли я получить индекс? Но кажется, что сгенерированные данные не имеют индекса?
output <- if (output_format == "list") {
res #this is output name defined before
} else if (output_format == "tsibble") {
as_tsibble(res)
}
return(output)
}
В качестве руководства я обновляю соответствующий пример для этой функции в Vignette. Тогда вещи становятся проводными.
Если бы я не сохранил сгенерированный вывод временного ряда (например, x ‹- my_function()), виньетка не смогла бы получиться. (Однако я могу использовать эту функцию непосредственно в независимом обычном файле RMD)
Использование этого кода напрямую может отображать вывод внутри RStudio, но не может быть связано.
my_function(seasonal.periods = c(7, 365), n = 800, nComp = 2,output_format="tsibble")
Error in Fun(X[[i]],...): 'list' object cannot be coerced to type 'integer' Calls: <Anonymous>...
as.data.frame -> head -> head.data.frame -> lappy -> FUN Execution halted.
Но это работает нормально. Он может вязать виньетку и показывает заглавные буквы.
x <- my_function(seasonal.periods = c(7, 365), n = 800, nComp = 2,output_format="tsibble")
head(x)
Однако очень неудобно каждый раз сохранять его перед использованием. Интересно, это из-за того, что в пакете есть какие-то настройки по умолчанию, или виньетка не меняется? Или есть какой-то дополнительный шаг, который мне нужно сделать после того, как я изменю функцию внутри пакета R? Или даже содержание if else, которое я добавляю, нуждается в улучшении?
Я попытался devtools::document("C:/Users/mreal/Documents/GitHub/package_name");devtools::install("C:/Users/mreal/Documents/GitHub/package_name")
обновить функцию перестроения. Но это все равно не помогает виньетке.
Я также пробовал rm(list=ls())
в console
. Это тоже не работает
Код, который я использовал в виньетке, показан ниже
Ссылка на гитхаб:
https://github.com/BocongZhao823/gratis/blob/master/vignettes/QuickStart.Rmd
---
title: "Introduction to gratis"
author: "Bocong Zhao"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Introduction to gratis}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
{r initial, echo = FALSE, cache = FALSE, results = 'hide'}
library(knitr)
opts_chunk$set(
warning = FALSE, message = FALSE, echo = TRUE,
fig.width = 7, fig.height = 6, fig.align = 'centre',
comment = "#>"
)
original <- options("tibble.print_min")
options(tibble.print_min = 5)
# <---- Do stuff with changed option, e.g. print some tibbles ---->
options(tibble.print_min = original)
{r, message=FALSE, include = FALSE}
library(forecast)
library(tsibble)
{r setup}
# load package
library(gratis)
## Generate mutiple seasonal time series
Time series can exhibit multiple seasonal pattern of different length, especially when series observed at a high frequency such as daily or hourly data.
We use function **generate_msts()** to generate mutiple seasonal time series.
**Definitions**
Here are the definitions of parameter settings in function generate_msts():
|parameter settings | Definition|
|:----|:-----|
|seasonal.periods | a vector of seasonal periods of the time series to be generated|
|nComp|number of mixing components when simulating time series using MAR models|
|n |length of the generated time series|
**Example**
Suppose we want to use MAR model to generate a time series with **2** mixing components and the length **800** from random parameter spaces. Particularly, this time series has two seasonal periods **7** and **365**.
{r fig.height = 6, fig.width = 7}
# Generate mutiple seasonal time series with 'tsibble' output format
x <- generate_msts(seasonal.periods = c(7, 365), n = 800, nComp = 2,output_format="tsibble")
head(x)
**Plot time series**
{r fig.height = 6, fig.width = 7}
# Generate mutiple seasonal time series with 'list' output format
x <- generate_msts(seasonal.periods = c(7, 365), n = 800, nComp = 2,output_format="list")
autoplot(x)
(сгенерированный файл.R) Код R, используемый внутри пакета, показан ниже
** Ссылка на гитхаб**
https://github.com/BocongZhao823/gratis/blob/master/R/generate_ts.R
#' Generate mutiple seasonal time series from random parameter spaces of the mixture autoregressive (MAR) models.
#'
#' Generate mutiple seasonal time series from random parameter spaces of the mixture autoregressive (MAR) models.
#' @param seasonal.periods a vector of seasonal periods of the time series to be generated.
#' @param n length of the generated time series.
#' @param nComp number of mixing components when simulating time series using MAR models.
#' @param output_format An optional argument which allows to choose output format between "list" and "tsibble"
#' @return a time series with multiple seasonal periods.
#' @export
#' @examples
#' x <- generate_msts(seasonal.periods = c(7, 365), n = 800, nComp = 2, output_format= "list")
#' forecast::autoplot(x)
generate_msts <- function(seasonal.periods = c(7, 365), n = 800, nComp = NULL,output_format="list") {
x.list <- map(seasonal.periods, function(p) {
generate_ts(n.ts = 1, freq = p, n = n, nComp = nComp)$N1$x
})
names(x.list) <- paste0("Season", seasonal.periods)
x.list[1:(length(x.list) - 1)] <- lapply(x.list[1:(length(x.list) - 1)], function(x) {
x - trendcycle(stl(x, "per"))
})
weights <- msts_weights(length(seasonal.periods))
res <- as_tibble(scale(x.list %>% bind_cols())[, ]) %>%
mapply("*", ., weights) %>%
as_tibble() %>%
mutate(x = rowSums(.)) %>%
select(x) %>%
msts(seasonal.periods = seasonal.periods)
# New content
output <- if (output_format == "list") {
res
} else if (output_format == "tsibble") {
as_tsibble(res)
}
return(output)
}
# ===========================================================================
# Simulated weights for the simulation of msts
# ===========================================================================
msts_weights <- function(n.periods) {
gamma <- runif(n.periods, 0)
weights <- gamma / sum(gamma)
return(weights)
}
else if( output_format == "tsibble") {res <- map(res, ~ {.x <- as_tsibble(.x$x); .x})}
- person akrun   schedule 09.09.2020.x$x <- as_tsibble(.x$x)
- person akrun   schedule 09.09.2020tibble::as_tsibble
вместоas_tsibble
? Идея заключалась в том, что он может странно загружать пакеты, поэтому указание «где» может устранить путаницу. - person Oliver   schedule 09.09.2020