我想询问有关将数据帧(或tibble)转换为tsibble的最有效方法的建议。
数据帧在第一列中有日期,所有其他列都用在相应日期给出的值表示不同的时间序列。我想高效地创建一个tsibble,其中key =每个时间序列的名称,index =每个日期。
因此,输出将是一个tsibble,如下所示:
Key Index Value
TimeSeriesOne FirstDate Value TimeSeriesOne on first date
TimeSeriesOne SecondDate Value TimeSeriesOne on second date
......................................................................
TimeSeriesOne LastDate Value TimeSeriesOne on last date
TimeSeriesTwo FirstDate Value TimeSeriesTwo on first date
......................................................................
TimeSeriesN LastDate Value TimeSeriesN on last date输入数据示例:
numRows <- 15
startDate <- lubridate::as_date('2018-06-10')
endDate <- startDate + base::months(x = numRows-1)
theDates <- base::seq.Date(
from = startDate,
to = endDate,
by = "month")
inputData <- tibble::tibble(
"Dates" = theDates,
"SeriesOne" = stats::rnorm(numRows),
"SeriesTwo" = stats::rnorm(numRows),
"SeriesThree" = stats::rnorm(numRows),
"SeriesFour" = stats::rnorm(numRows))发布于 2020-01-06 04:59:32
你可以使用tidyr转换为“长格式”
tsibble_input <- tidyr::pivot_longer(inputData, cols = -Dates, names_to = "Key", values_to = "Value") 并获取tsibble
tsibble::as_tsibble(tsibble_input, index = "Dates", key = "Key")发布于 2020-01-06 04:36:10
我们可以使用data.table中的melt来高效地完成此操作,然后将其转换为tibble
library(data.table)
library(tibble)
as_tibble(melt(setDT(inputData), id.var = 'Dates', variable.name = 'Key',
value.name = 'Value')[, Key := paste0("Time", Key)])发布于 2020-01-06 04:52:44
转换为zoo,然后转换为长数据帧,最后转换为tsibble
library(tsibble)
library(zoo)
inputData %>%
read.zoo %>%
fortify.zoo(melt = TRUE) %>%
as_tsibble(key = "Series", index = "Index")或者使用stack (或许多其他整形功能中的任何一个,包括整形、熔化、聚集、pivot_longer)来创建长数据帧,然后进行缩略。如果您所说的高效是指最小的前提条件,那么这只使用tsibble包及其依赖项。
library(tsibble)
inputData %>%
{ cbind(.[1], stack(.[-1])) } %>%
as_tsibble(key = "ind", index = "Dates")https://stackoverflow.com/questions/59603629
复制相似问题