简体   繁体   English

R - xts 对象中每月的观察次数(工作日数据)

[英]R - Number of observations per month in an xts object (weekday data)

I have several xts-objects containing weekday data from 2001-01-01 to 2021-12-31.我有几个 xts 对象,其中包含从 2001 年 1 月 1 日到 2021 年 12 月 31 日的工作日数据。 Now I need to know the number of observations within each month from January 2001 to December 2021 in order to further analyse them.现在我需要知道从 2001 年 1 月到 2021 年 12 月每个月的观察次数,以便进一步分析它们。 How can I get these?我怎样才能得到这些? I'm rather new to R (and programming), so I assume there is a simple formula for this I am unaware of.我对 R(和编程)相当陌生,所以我认为有一个我不知道的简单公式。

    structure(c(6.5156, 6.5, 6.4531, 6, 5.8594, 5.8281, 5.8438, 5.8281, 
5.8438, 5.8438, 5.8438, 5.7969), class = c("xts", "zoo"), .CLASS = "double", index = structure(c(978307200, 
978393600, 978480000, 978566400, 978652800, 978912000, 978998400, 
979084800, 979171200, 979257600, 979516800, 979603200), tzone = "UTC", tclass = "Date"), .Dim = c(12L, 
1L))

First I convert your xts object to a dataframe.首先,我将您的 xts 对象转换为数据框。 After that you can create a month column using month from lubridate and group_by per month to summarise the number of observations per month like this:之后,您可以使用month来自lubridategroup_by的月份创建一个month列,以summarise每月的观察次数,如下所示:

library(dplyr)
library(lubridate)
data.frame(date = index(df), coredata(df)) %>%
  mutate(month = month(date)) %>%
  group_by(month) %>%
  summarise(n = n())

Output:输出:

# A tibble: 1 × 2
  month     n
  <int> <int>
1     1    12

In this case your data has 12 observations in January.在这种情况下,您的数据在一月份有 12 个观测值。

xts has all kinds of period.apply functions you can use. xts 有各种period.apply你可以使用的功能。 for monthly: apply.monthly每月: apply.monthly

Based on your example if you want the sum / mean / n of observations:根据您的示例,如果您想要观察的总和/平均值/ n:

# sum
apply.monthly(my_xts, sum)
              [,1]
2001-01-16 72.1564

# mean
apply.monthly(my_xts, mean)
               [,1]
2001-01-16 6.013033

# n of records 
# length works like sum or mean, 
# but this is an example of how to use an anonymous function.
apply.monthly(my_xts, function(x) length(x))
           [,1]
2001-01-16   12

xts always takes the last day of the period to show the information. xts 总是在期间的最后一天显示信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM