0

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

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 数据。

#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.
4

1 回答 1

1

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

library(dplyr)
library(tsibble)

data <- ex %>%
  mutate(key  = row_number()) %>%
  as_tsibble(index = date_time, key = key)
于 2021-05-31T08:47:13.347 回答