【发布时间】:2014-02-26 12:32:55
【问题描述】:
我正在尝试在选定交易日的股票价格和同一天对这些股票的观察(我们称之为“Nx 观察”)之间进行动物园合并。有时在股票交易日没有 Nx 观察,有时我们在非交易日有 Nx 观察。我们想要放置一个“NA”,我们在交易日没有任何 Nx 观察结果,但在非交易日有 Nx 观察结果时消除 Nx 观察结果,因为没有同一天的交易数据,Nx 观察结果是无用的。
以下 SO 问题与我很接近,但我会将这个问题描述为替换缺失数据,而我的目标是真正消除在非交易日进行的观察(如有必要,我们可以更改 Nx 观察的过程被采取,但不理会它会是一个更便宜的解决方案)。
merge data frames to eliminate missing observations
我准备说明的脚本如下(我是 R 和 SO 的新手;欢迎所有建议):
# create Stk_data data.frame for use in the Stack Overflow question
Date_Stk <- c("1/2/13", "1/3/13", "1/4/13", "1/7/13", "1/8/13") # dates for stock prices used in the example
ABC_Stk <- c(65.73, 66.85, 66.92, 66.60, 66.07) # stock prices for tkr ABC for Jan 1 2013 through Jan 8 2013
DEF_Stk <- c(42.98, 42.92, 43.47, 43.16, 43.71) # stock prices for tkr DEF for Jan 1 2013 through Jan 8 2013
GHI_Stk <- c(32.18, 31.73, 32.43, 32.13, 32.18) # stock prices for tkr GHI for Jan 1 2013 through Jan 8 2013
Stk_data <- data.frame(Date_Stk, ABC_Stk, DEF_Stk, GHI_Stk) # create the stock price data.frame
# create Nx_data data.frame for use in the Stack Overflow question
Date_Nx <- c("1/2/13", "1/4/13", "1/5/13", "1/6/13", "1/7/13", "1/8/13") # dates for Nx Observations used in the example
ABC_Nx <- c(51.42857, 51.67565, 57.61905, 57.78349, 58.57143, 58.99564) # Nx scores for stock ABC for Jan 1 2013 through Jan 8 2013
DEF_Nx <- c(35.23809, 36.66667, 28.57142, 28.51778, 27.23150, 26.94331) # Nx scores for stock DEF for Jan 1 2013 through Jan 8 2013
GHI_Nx <- c(7.14256, 8.44573, 6.25344, 6.00423, 5.99239, 6.10034) # Nx scores for stock GHI for Jan 1 2013 through Jan 8 2013
Nx_data <- data.frame(Date_Nx, ABC_Nx, DEF_Nx, GHI_Nx) # create the Nx scores data.frame
# create zoo objects & merge
z.Stk_data <- zoo(Stk_data, as.Date(as.character(Stk_data[, 1]), format = "%m/%d/%Y"))
z.Nx_data <- zoo(Nx_data, as.Date(as.character(Nx_data[, 1]), format = "%m/%d/%Y"))
z.data.outer <- merge(z.Stk_data, z.Nx_data)
2013 年 1 月 3 日 Nx 观测值的 NA 很好(我们将使用 na.locf),但我们需要消除 1 月 5 日和 6 日出现的 Nx 观测值以及股票价格中的相关 NA动物园对象的部分。
我已经阅读了 merge.zoo 的 R 文档关于“all”的使用:它的使用“允许 交集、并集和左右连接要表达”。但尝试所有组合 使用“all”之后产生了相同的结果(至于为什么会是次要问题)。
z.data.outer <- zoo(merge(x = Stk_data, y = Nx_data, all.x = FALSE)) # try using "all"
虽然我希望 cmets 关于第二个问题,但我主要感兴趣的是学习如何在没有股票交易的日子消除无关的 Nx 观察。谢谢。 (感谢社区对 R 的所有精彩解释!)
【问题讨论】: