在R中,不能在程序包Vignette文件中编织相同的代码. “列表"无法将对象强制为整数类型 [英] In R, the same code cannot be knit out in package Vignette file. "list" object cannot be coerced to type integer

查看:624
本文介绍了在R中,不能在程序包Vignette文件中编织相同的代码. “列表"无法将对象强制为整数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与GRATIS软件包中的generate_msts()函数有关.

This question is about generate_msts() function in package GRATIS.

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

I add some new stuff (make the function has options to transform its output into a lovely tsibble format or keep the original ‘list’ format) and prepare update to CRAN.

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

New code add as below (detail of the codes with example shown at the bottom of the question)

我想知道我是否应该整理索引?但是生成的数据似乎没有索引吗?

  output <- if (output_format == "list") {
    res                                    #this is output name defined before
  } else if (output_format == "tsibble") {
    as_tsibble(res)
  }
  return(output)
}

作为指导,我在 Vignette 中更新了此功能的相应示例.然后事情就变成有线了.

And as a guidance, I update the corresponding example for this function in Vignette. Then things become wired.

如果我没有保存生成的时间序列输出(例如x<-my_function()),则渐晕 无法编织. (但是,我可以在独立的普通RMD文件中直接使用此功能)

If I did not save the generated time series output (e.g. x <- my_function()), the vignette cannot knit out. (However, I can use this function directly in an independent normal RMD file)

直接使用此代码可以在RStudio内显示输出,但不能编织出来.

Use this code directly can show output inside RStudio, but cannot be knit out.

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.

但是,这很好.它可以编织出小插图并显示小头的头部.

But, this works fine. It can knit out the vignette and shows head of tsibble.

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

但是,每次使用它之前都保存起来很不方便.我想知道这是否是因为我在程序包或小插图中使用的任何默认设置都不会更改吗?还是在更改R包中的功能后需要做一些额外的步骤?甚至我需要添加的其他内容是否需要改进?

我尝试过devtools::document("C:/Users/mreal/Documents/GitHub/package_name");devtools::install("C:/Users/mreal/Documents/GitHub/package_name")更新重建功能.但这仍然无助于装饰图案.

I have tried devtools::document("C:/Users/mreal/Documents/GitHub/package_name");devtools::install("C:/Users/mreal/Documents/GitHub/package_name") to update the re-build function. But this still does not help vignette.

我也在console中尝试了rm(list=ls()).效果不佳

I also tried rm(list=ls()) in console. It does not work as well

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

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链接**

** Github link**

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

推荐答案

我试图为您运行此程序-我的第一个猜测是名称空间问题.但这似乎也与generate_msts()函数有关.

I tried to run this for you - my first guess was a NAMESPACE problem. But it seems also related to the generate_msts() function.

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

I really don't think this has to do with first saving it to a variable 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"))

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

In the failure cases it is always the same error message as for you:

错误:处理小插图'QuickStart.Rmd'失败,并显示以下诊断信息: 'list'对象不能强制输入'integer'

Error: processing vignette 'QuickStart.Rmd' failed with diagnostics: 'list' object cannot be coerced to type 'integer'

因此,由于head()str()class()始终对我有用,并且只有print()不起作用,因此我认为这是打印功能存在的问题.因此,将其保存到变量x中的方法只能正常工作,因为您没有调用打印功能.

So since head(), str(), class() always worked for me and only print() did not work, I am assuming it is a problem with the print function. So your workaround with saving it into variable x only worked fine, because you did not call the print function.

同样重要的是该问题仅在Rmarkdown 中使用generate_msts()时才发生.正如我稍后解释的那样,这似乎是合理的,因为在knitr中进行打印不同于在控制台上进行打印.

Also important the problem only occurred for me when using generate_msts() inside Rmarkdown. As I explain later this seems reasonable, since printing in knitr is different from printing on the console.

当我更改您的generate_msts()并重建软件包时:

When I alter your generate_msts() and rebuild the package:

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

Rmarkdown突然运行而没有错误.

The Rmarkdown suddenly runs without an error.

我猜想 print()可能是您与knitr交互时使用的特定数据的问题.

My guess would be it is a problem with the print() for your specific data in interaction with knitr.

在knitr中进行打印似乎与在控制​​台上进行打印有所不同(这可能是为什么不使用rmarkdown就能进行打印的原因)

Printing in knitr seems to be different from printing on the console (might be why it works without rmarkdown)

以下是有关自定义打印方法和编织的一个不错的链接: https://cran.r-project.org/web/packages/knitr/vignettes/knit_print.html

Here is a nice link about custom print methods and knitr: https://cran.r-project.org/web/packages/knitr/vignettes/knit_print.html

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

Before knitr v1.6, printing objects in R code chunks basically emulates the R console.

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

I could imagine the S3 method for knit_print from the tsibble package (which just uses all the printing methods from tibble?) might just not work properly for your specific dataset (I mean it worked for the tsibble I created with tsibble() ). But just a (wild?) guess...the error and behavior overall is really strange ...

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

Here is also the R Markdown callstack for the error:

 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文档中使用以下命令

Should be similar for you, but if you want to get this on your own, you have to the following commands to your rmarkdown document

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,...并导致错误.

But as you can see in the callstack, the error is caused by base::print(x), which calls the S3 method tibble:::print.tbl(x), this method then internally calls tsibble:::format.tbl_ts, which calls tibble::trunc_mat, ... and somewhere inside the error is caused.

好吧...接下来我会继续做这些事情...最终,这些函数调用中的混乱是您在开始时设置的knitr选项.

Ok ... I followed this further down the road and ... what in the end messes inside these function calls, are the knitr options you set in the beginning.

您在rmarkdown的开头写道:

You write at the beginning of your 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)

那应该可以工作.

这篇关于在R中,不能在程序包Vignette文件中编织相同的代码. “列表"无法将对象强制为整数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆