首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R: Tibble转换

R: Tibble转换
EN

Stack Overflow用户
提问于 2020-12-28 13:26:14
回答 1查看 100关注 0票数 0

我使用的是R编程语言。我在这里遵循这个教程:https://blogs.rstudio.com/ai/posts/2018-06-25-sunspots-lstm/

我正在尝试以与这里的示例相同的方式准备数据:

代码语言:javascript
复制
# 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。

我认为,我应该能够以类似的形式模拟数据(使用与教程中的数据相同的名称):

代码语言:javascript
复制
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

现在,当我尝试将文件转换为所需的格式时:

代码语言:javascript
复制
 y.mon_mod <- y.mon%>%
     tk_tbl() %>%
     mutate(index = as_date(index)) %>%
     as_tbl_time(index = index)

我得到以下错误:

代码语言:javascript
复制
  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.

有人知道为什么会发生这个错误吗?我检查了我的环境,它显示“名称空间”库已经加载。是不是因为我的"date“(index)变量的格式不正确?有人知道如何解决这个问题吗?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-28 15:17:10

使您的index列可以转换为date对象。

代码语言:javascript
复制
library(dplyr)
library(lubridate)
library(tibbletime)
library(timetk)

y.mon %>%
  mutate(index = paste0(index, '/01')) %>%
  tk_tbl() %>%
  mutate(index = as_date(index)) %>%
  as_tbl_time(index = index) ->  y.mon
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65473333

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档