首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在tsibble数据转换中设置键

在tsibble数据转换中设置键
EN

Stack Overflow用户
提问于 2021-05-31 16:13:07
回答 1查看 59关注 0票数 0

在tsibbledata包中,vic_elec数据键看起来像行键。

代码语言:javascript
复制
library(tsibble)
library(tsibbledata)
library(lubridate)
data('vic_elec')
str(vic_elec)
str(dt)
tsibble [52,608 x 5] (S3: tbl_ts/tbl_df/tbl/data.frame)
 $ Time       : POSIXct[1:52608], format: "2012-01-01 00:00:00" "2012-01-01 00:30:00" "2012-01-01 01:00:00" "2012-01-01 01:30:00" ...
 $ Demand     : num [1:52608] 4383 4263 4049 3878 4036 ...
 $ Temperature: num [1:52608] 21.4 21.1 20.7 20.6 20.4 ...
 $ Date       : Date[1:52608], format: "2012-01-01" "2012-01-01" "2012-01-01" "2012-01-01" ...
 $ Holiday    : logi [1:52608] TRUE TRUE TRUE TRUE TRUE TRUE ...
 - attr(*, "key")= tibble [1 x 1] (S3: tbl_df/tbl/data.frame)
  ..$ .rows: list<int> [1:1] 
  .. ..$ : int [1:52608] 1 2 3 4 5 6 7 8 9 10 ...
  .. ..@ ptype: int(0) 
 - attr(*, "index")= chr "Time"
  ..- attr(*, "ordered")= logi TRUE
 - attr(*, "index2")= chr "Time"
 - attr(*, "interval")= interval [1:1] 30m
  ..@ .regular: logi TRUE

但在转换时,我的数据不能使用row.name作为键。当我找不到可以使用键的值时,如何像vic_elec数据一样应用行名键。

代码语言:javascript
复制
#data example    
ex <- data.frame(date_time = c("2020-01-01","2020-01-01","2020-01-02","2020-01-02","2020-01-03","2020-01-03","2020-01-04","2020-01-04"),
                     temperature = c(12,14,15,18,16,11,17,17),
                     humidity = c(78,82,76,72,71,75,74,71))

ex$date_time<- as.Date(ex$date_time)
ex
date_time  temperature  humidity
2020-01-01          12        78
2020-01-01          14        82
2020-01-02          15        76
2020-01-02          18        72
2020-01-03          16        71
2020-01-03          11        75
2020-01-04          17        74
2020-01-04          17        71
> ex %>%as_tsibble(index = date_time)
Error: A valid tsibble must have distinct rows identified by key and index.
i Please use `duplicates()` to check the duplicated rows.
Run `rlang::last_error()` to see where the error occurred.
> ex %>%as_tsibble(key = row.names(ex), index = date_time)
Error: Can't subset columns that don't exist.
x Columns `1`, `2`, `3`, `4`, `5`, etc. don't exist.
EN

回答 1

Stack Overflow用户

发布于 2021-05-31 16:47:13

您可以使用row_number()创建新列并将其用作键。

代码语言:javascript
复制
library(dplyr)
library(tsibble)

data <- ex %>%
  mutate(key  = row_number()) %>%
  as_tsibble(index = date_time, key = key)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67770077

复制
相关文章

相似问题

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