【问题标题】:Use endpoints function to get start points instead?使用端点函数来获取起点?
【发布时间】:2015-01-14 22:01:39
【问题描述】:

我有一个名为 Daily_Quotes 的 xts 对象,其中包含股票报价。我正在使用endpoints 来获取我使用getSymbols(来自quantmod 包)检索到的每月股票报价。我注意到endpoints 函数为包含特定月份的最后一个交易日的行创建了一个索引,并将其分配给指定日期范围内的新对象。反正有没有得到本月的第一个交易日?

# My code    
Monthly_Quotes <- Daily_Quotes[endpoints(Daily_Quotes,'months')]

我尝试做的是:

# This gave me the next day or 1st day of the next month
# or next row for the object.
endpoints(Daily_Quotes,'months') + 1

# So I applied this and it gave me 
# Error in `[.xts`(Daily_Quotes, endpoints(Daily_Quotes, "months") + 1) :
# subscript out of bounds
Monthly_Quotes <- Daily_Quotes[endpoints(Daily_Quotes,'months') + 1]

我该如何解决这个问题?

【问题讨论】:

  • 通常最好不要将答案编辑到您的问题中。我们试图将问题和答案分开。如果有人现在阅读您的问题,那么您在问什么就不太清楚了,因为它说“我该如何尝试解决这个问题?”然后是解决方案。
  • @GSee:出于这个原因,我回滚了这些编辑。
  • 感谢 Joshua,因为我打算自己编辑它。 @Gsee 将继续这样做。

标签: r xts


【解决方案1】:

您可以像这样创建startpoints 函数

startpoints <- function (x, on = "months", k = 1) {
  head(endpoints(x, on, k) + 1, -1)
}

【讨论】:

  • 谢谢。效果很好。
  • 我需要了解 -1 参数。我知道“head(endpoints(x,on,k)+ 1)”根据k元素给了我每个索引值的x数量+ 1个月。到目前为止,一切都很好?执行 "head(endpoints(Daily_Quotes,'months', 1) + 1, -1)" 时,它会根据 k 给我每个月的索引值 + 1,加上 -1 会返回所有索引值。所以我看到了区别,但不知道这是如何工作的?我希望我的问题是有道理的。我是否过度分析或提出了一个合理的问题?
  • @NewComer head(x, -1) 等价于x[-length(x)](如果您查看xts:::startof,这就是实现相同功能的方式)。 ?head 表示如果n 为负数,“除了n 的最后/第一个元素数量之外的所有x。”这有帮助吗?
  • 这绝对有帮助。我将研究 xts:::startof。谢谢你的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2019-01-03
  • 1970-01-01
  • 2019-06-22
  • 2022-08-16
  • 2013-04-01
  • 1970-01-01
相关资源
最近更新 更多