簡體   English   中英

R:將xts或zoo對象轉換為數據框

[英]R: converting xts or zoo object to a data frame

什么是將時間序列數據強制轉換為數據幀的簡單方法,其格式是結果數據是原始數據的摘要?

這可能是一些示例數據,存儲在xts或zoo對象中:

t,                  V1
"2010-12-03 12:00", 10.0
"2010-11-04 12:00", 10.0
"2010-10-05 12:00", 10.0
"2010-09-06 12:00", 10.0
...and so on, monthly data for many years.

我想將其轉換為數據框,如:

year, month, V1
2010, 12,    a descriptive statistic calculated of that month's data
2010, 11,    ...
2010, 10,    ...
2010, 9,     ...

我問這個的原因是因為我想在同一個圖中繪制每月計算的數據摘要。 對於后一種格式的數據,我可以很容易地做到這一點,但是沒有找到時間序列格式的繪圖方法。

例如,我可以在每日間隔內測量幾年的溫度數據,我想繪制同一地塊中每年月平均溫度的曲線。 我沒有弄清楚如何使用xts格式的數據來做這件事,或者如果這甚至適合數據的xts / zoo格式化的目的,這似乎總是隨身攜帶年份信息。

請提供一份可供使用的數據樣本,我將盡力提供一般性答案。 基本上,您可以使用apply.monthly來計算xts對象的摘要統計信息。 然后,您可以將索引轉換為yearmon並將xts對象轉換為data.frame。

x <- xts(rnorm(50), Sys.Date()+1:50)
mthlySumm <- apply.monthly(x, mean)
index(mthlySumm) <- as.yearmon(index(mthlySumm))
Data <- as.data.frame(mthlySumm)

這是使用tidyquant包的解決方案,其中包括用於將數據幀強制轉換為xts對象的函數as_xts()用於將xts對象as_tibble()為tibbles(“整潔”數據幀)的as_tibble()。

重新創建數據:

> data_xts
           V1
2010-09-06 10
2010-10-05 10
2010-11-04 10
2010-12-03 10

使用as_tibble()轉換為as_tibble() preserve_row_names = TRUE添加一個名為“row.names”的列,其中xts索引為字符類。 renamemutate用於清理日期。 輸出是具有日期和值的元素。

> data_df <- data_xts %>%
     as_tibble(preserve_row_names = TRUE) %>%
     rename(date = row.names) %>%
     mutate(date = as_date(date))
> data_df
# A tibble: 4 × 2
        date    V1
      <date> <dbl>
1 2010-09-06    10
2 2010-10-05    10
3 2010-11-04    10
4 2010-12-03    10

您可以更進一步,使用mutate函數添加其他字段,如日,月和年。

> data_df %>%
     mutate(day   = day(date),
            month = month(date),
            year  = year(date))
# A tibble: 4 × 5
        date    V1   day month  year
      <date> <dbl> <int> <dbl> <dbl>
1 2010-09-06    10     6     9  2010
2 2010-10-05    10     5    10  2010
3 2010-11-04    10     4    11  2010
4 2010-12-03    10     3    12  2010

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM