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 に答える