【发布时间】:2017-05-28 14:06:38
【问题描述】:
我从雅虎下载了股市数据(代码如下)——为了上下文,起初我尝试使用getSymbols(^DJI),但我收到了可能与雅虎有关的错误消息......不同的问题。
关键是,一旦下载并导入到 R 中,我将其调整为足够接近时间序列的格式,以便能够运行 chartSeries(DJI):
require(RCurl)
require(foreign)
x <- getURL("https://raw.githubusercontent.com/RInterested/datasets/gh-pages/%5EDJI.csv")
DJI <- read.csv(text = x, sep =",")
DJI$Date <- as.Date(DJI$Date, format = "%m/%d/%Y") # Formatting Date as.Date
rownames(DJI) <- DJI$Date # Assigning Date to row names
DJI$Date <- NULL # Removing the Date column
chartSeries(DJI, type="auto", theme=chartTheme('white'))
即使数据集不是真正的时间序列:
> is.ts(DJI)
[1] FALSE
当我试图找出例如道琼斯指数最低收盘价的日期时,问题就出现了。我可以做类似的事情
> DJI[DJI$Close == min(DJI$Close),]
Open High Low Close Adj.Close Volume
1985-05-01 1257.18 1262.81 1239.07 1242.05 1242.05 10050000
产生整行,包括行名 (1985-05-01),这是我想要的唯一部分。但是,如果我坚持只获取实际日期,我必须处理第二个数据集,其中包含其中一列中的日期:
require(RCurl)
require(foreign)
x <- getURL("https://raw.githubusercontent.com/RInterested/datasets/gh-pages/%5EDJI.csv")
DJI <- read.csv(text = x, sep =",")
DJI$Date <- as.Date(DJI$Date, format = "%m/%d/%Y") # Formatting Date as.Date
rownames(DJI) <- DJI$Date # Assigning Date to row names
DJI.raw <- DJI # Second dataset for future subsetting
DJI$Date <- NULL # Removing the Date column
这确实让我可以跑步
> DJI.raw$Date[DJI.raw$Close == min(DJI.raw$Close)]
[1] "1985-05-01"
此外,我不认为将数据集转换为 .xts 文件会有帮助。
【问题讨论】:
-
请注意,当您将日期分配给行名时,它们会变回字符。话虽这么说,如果您不希望 data.frame 中的另一列包含日期并且您可以将日期作为字符,您可以简单地执行
rownames(DJI)[DJI$Close == min(DJI$Close)] -
@digEmAll 我假设时间序列要求行名是日期。这不是真的吗?此外,如果我将 Date 列保留在数据集中,我将无法运行
chartSeries()... -
是的,这是可能的(我不知道 chartSeries 函数),但这并不意味着您不能在 data.frame 中拥有列,并且只将列子集传递给 chartSeries.. . 例如
chartSeries(DJI[,-1], type="auto", theme=chartTheme('white'))(-1 表示我们没有将位置 1 的列传递给 chartSeries,当然如果 Date 列位于位置 2,您应该传递 -2 等等...) -
@digEmAll 关于需要日期信息的行名的部分是否正确?
-
我不知道,我什至不知道chartSeries是从哪里来的……