【发布时间】:2021-04-04 23:20:06
【问题描述】:
我正在使用 R 编程语言。我在这里关注本教程:https://blogs.rstudio.com/ai/posts/2018-06-25-sunspots-lstm/
我正在尝试以与此处示例相同的方式准备数据:
# Core Tidyverse
library(tidyverse)
library(glue)
library(forcats)
# Time Series
library(timetk)
library(tidyquant)
library(tibbletime)
# Visualization
library(cowplot)
# Preprocessing
library(recipes)
# Sampling / Accuracy
library(rsample)
library(yardstick)
# Modeling
library(keras)
library(tfruns)
#here is what I am trying to copy
sun_spots <- datasets::sunspot.month %>%
tk_tbl() %>%
mutate(index = as_date(index)) %>%
as_tbl_time(index = index)
sun_spots
# A time tibble: 3,177 x 2
# Index: index
index value
<date> <dbl>
1 1749-01-01 58
2 1749-02-01 62.6
3 1749-03-01 70
4 1749-04-01 55.7
5 1749-05-01 85
6 1749-06-01 83.5
7 1749-07-01 94.8
8 1749-08-01 66.3
9 1749-09-01 75.9
10 1749-10-01 75.5
# ... with 3,167 more rows
在本例中,格式化数据的维度为 3,177 x 2。
我想,我应该能够以类似的形式模拟数据(使用与教程中的数据相同的名称):
index = seq(as.Date("1749/1/1"), as.Date("2016/1/1"),by="day")
index <- format(as.Date(index), "%Y/%m/%d")
value <- rnorm(97520,27,2.1)
final_data <- data.frame(index, value)
y.mon<-aggregate(value~format(as.Date(index),
format="%Y/%m"),data=final_data, FUN=sum)
y.mon$index = y.mon$`format(as.Date(index), format = "%Y/%m")`
y.mon$`format(as.Date(index), format = "%Y/%m")` = NULL
#resulting file is y.mon
现在,当我尝试将文件转换为所需格式时:
y.mon_mod <- y.mon%>%
tk_tbl() %>%
mutate(index = as_date(index)) %>%
as_tbl_time(index = index)
我收到以下错误:
Error: Problem with `mutate()` input `index`.
x 'origin' must be supplied
i Input `index` is `as_date(index)`.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
In tk_tbl.data.frame(.) :
Warning: No index to preserve. Object otherwise converted to tibble successfully.
有谁知道为什么会发生这个错误?我检查了我的环境,它说“命名空间”库已加载。是因为我的“日期”(索引)变量格式不正确吗?有人知道如何解决这个问题吗?
谢谢
【问题讨论】:
-
y.mon是您的代码生成的对象,而不是datasets包中的对象。所以只需在y.mon之前去掉datasets::,代码就可以工作了。 -
补充上面@neilfws 所说的内容,每当您看到一个名称后跟
::时,这意味着您正在从::之前的包中调用一个函数或对象。所以datasets::sunspot.month的意思是“来自 sunspots 包,使用对象 sunspots.month。”您创建了对象y.mon,但它在包sunspots中不存在,因此出现错误“错误:'y.mon' 不是来自'namespace:datasets' 的导出对象。” -
感谢您的回复!我尝试了以下代码: y.mon_mod % tk_tbl() %>% mutate(index = as_date(index)) %>% as_tbl_time(index = index);我收到以下错误:错误:
mutate()输入问题index。 x 'origin' 必须提供 i 输入index是as_date(index)。运行rlang::last_error()以查看错误发生的位置。另外:警告消息:在 tk_tbl.data.frame(.) 中:警告:没有要保留的索引。否则对象成功转换为 tibble。 ...可能是日期格式错误? -
感谢你们两位的cmets!我将从问题中删除 ::datasets 命令
标签: r date keras time-series data-manipulation