首页 > 解决方案 > 在 R 中,无法在包 Vignette 文件中编写相同的代码。“列表”对象不能被强制输入整数

问题描述

这个问题是关于 GRATIS 包中的 generate_msts() 函数。

我添加了一些新内容(使该函数具有将其输出转换为可爱的 tsibble 格式或保留原始“列表”格式的选项)并准备对 CRAN 的更新。

新代码添加如下(代码的详细信息以及问题底部显示的示例)

我想知道我应该得到 tsibble 索引吗?但是生成的数据好像没有索引?

  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。它也不起作用

我在小插图中使用的代码如下

Github 链接:

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代码如下

** Github 链接**

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)
}

标签: rfunctionvignettetsibble

解决方案


我试图为你运行这个 - 我的第一个猜测是一个 NAMESPACE 问题。但它似乎也与generate_msts()功能有关。

我真的不认为这与首先将其保存到变量有关x

以下是我的发现:

不工作:

x <- generate_msts(seasonal.periods = c(7, 365), n = 800, nComp = 2,output_format="tsibble")

x

不工作:

print(generate_msts(seasonal.periods = c(7, 365), n = 800, nComp = 2,output_format="tsibble"))

不工作:

x <- generate_msts(seasonal.periods = c(7, 365), n = 800, nComp = 2,output_format="tsibble")

print(x)

作品:

 head(generate_msts(seasonal.periods = c(7, 365), n = 800, nComp = 2,output_format="tsibble"))

在失败的情况下,它总是与您相同的错误消息:

错误:处理小插图“QuickStart.Rmd”因诊断失败:“列表”对象不能被强制输入“整数”

因此,既然,head()一直为我工作,只是没有工作,我假设这是打印功能的问题。因此,您将其保存到变量中的解决方法只能正常工作,因为您没有调用 print 函数。str()class()print()x

同样重要的是,只有在使用 generate_msts() inside 时才会出现问题Rmarkdown。正如我稍后解释的那样,这似乎是合理的,因为在 knitr 中打印与在控制台上打印不同。

当我改变你generate_msts()并重建包时:

output <- if (output_format == "list") {
    res
  } else if (output_format == "tsibble") {
    tsibble(date = as.Date("2017-01-01") + 0:9,value = rnorm(10))
  }

Rmarkdown 突然运行没有错误。

我的猜测是与 knitr 交互的特定数据的print()存在问题。

在 knitr 中打印似乎与在控制​​台上打印不同(可能是它在没有 rmarkdown 的情况下工作的原因)

这是关于自定义打印方法和 knitr 的一个很好的链接: https ://cran.r-project.org/web/packages/knitr/vignettes/knit_print.html

在 knitr v1.6 之前,在 R 代码块中打印对象基本上模拟了 R 控制台。

我可以想象 tsibble 包中用于 knit_print 的 S3 方法(它只使用 tibble 中的所有打印方法?)对于您的特定数据集可能无法正常工作(我的意思是它适用于我创建的 tsibble tsibble())。但只是一个(疯狂的?)猜测......整体的错误和行为真的很奇怪......

编辑:这也是错误的 R Markdown 调用堆栈:

 1. ├─base::print(x)
  2. └─tibble:::print.tbl(x)
  3.   ├─cli::cat_line(format(x, ..., n = n, width = width, n_extra = n_extra))
  4.   │ └─base::paste0(..., collapse = "\n")
  5.   ├─base::format(x, ..., n = n, width = width, n_extra = n_extra)
  6.   └─tsibble:::format.tbl_ts(x, ..., n = n, width = width, n_extra = n_extra)
  7.     ├─base::format(trunc_mat(x, n = n, width = width, n_extra = n_extra))
  8.     └─tibble::trunc_mat(x, n = n, width = width, n_extra = n_extra)
  9.       ├─base::as.data.frame(head(x, n))
 10.       ├─utils::head(x, n)
 11.       └─utils:::head.data.frame(x, n)
 12.         └─base::lapply(...)
 13.           └─utils:::FUN(X[[i]], ...)

对你来说应该是类似的,但如果你想自己得到这个,你必须在你的 rmarkdown 文档中使用以下命令

options(rlang_trace_top_env = rlang::current_env())
options(error = function() {
  sink()
  print(rlang::trace_back(bottom = sys.frame(-1)), simplify = "none")
})

但是正如你在调用栈中看到的,错误是由base::print(x)引起的,它调用了S3方法tibble:::print.tbl(x),然后这个方法内部调用了tsibble:::format.tbl_ts , 它调用 tibble::trunc_mat, ... 并且在某个地方引起了错误。

好的......我沿着这条路走得更远......最终这些函数调用中的混乱是你在开始时设置的 knitr 选项。

您在 rmarkdown 的开头写道:

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)

将其更改为:

options(tibble.print_min = 5)

那时应该工作。


推荐阅读