R:将每日数据转换为每周数据

时间:2019-03-11 17:11:51

标签: r

当使用to.weekly将以下每日数据转换为每周频率时,我在第5列和第6列中遇到错误: 原始每日数据:第5列:调整后价格;第6列:交易量 转换为每周数据:第5列:交易量(每周)和第6列:调整后的价格(以名称计算),但包含交易量数据

data.AMZN<-read.table(text=
          "AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Adjusted AMZN.Volume
2011-01-03    181.37    186.00   181.21     184.22        184.22     5331400
2011-01-04    186.15    187.70   183.78     185.01        185.01     5031800
2011-01-05    184.10    187.45   184.07     187.42        187.42     3418800
2011-01-06    186.50    187.41   185.25     185.86        185.86     3179700
2011-01-07    187.88    188.45   183.74     185.49        185.49     5221700")

data.weekly<-read.table(text=
           "wk.Open wk.High wk.Low wk.Close wk.Volume wk.Adjusted
2010-12-31  181.96  182.30 179.51   180.00   3451900     3451900
2011-01-07  181.37  188.45 181.21   185.49  22183400     5221700
2011-01-14  185.04  188.94 182.51   188.75  15899000     3662800
2013-12-31  399.41  399.92 392.45   398.79   4483600     1996500")

1 个答案:

答案 0 :(得分:0)

我不太清楚您在data.AMZNdata.weekly之间做了什么。请注意,数据中的日期不是变量,而是行名。因此,首先要做的就是将名称移到列。

我建议对您的数据进行以下操作:

library(tidyverse)
library(lubridate)
data.weekly2 = data.AMZN %>%
  rownames_to_column(., "date")%>% # as the name suggests
  mutate(date = ymd(date)) %>% # convert characters to date
  mutate( week_start = floor_date(date, "week")) %>% # creates column with week start date
  group_by(week_start) %>% # now yo can do with data what you need i.e.:
  summarise(AMZN.Volume = sum(AMZN.Volume))

祝一切顺利, M