在R中使用apply和用户定义的函数

时间:2014-01-24 04:31:30

标签: r function apply

我正在尝试将用户定义的函数augenSpike应用于存储在环境中的一组代码,但不知何故它不起作用。如果有人可以帮助这个入门级R用户,我将非常感谢......

library(quantmod)

slideapply <- function(x, n, FUN=sd) {
  v <- c(rep(NA, length(x)))
  for (i in n:length(x) ) {
    v[i] <- FUN(x[(i-n+1):i])
  } 
  return(v)   
}

augenSpike <- function(x, n=20) {
  prchg <- c(NA, diff(x))
  lgchg <- c(NA, diff(log(x)))
  stdevlgchg <- slideapply(lgchg, n, sd)
  stdpr <- x * stdevlgchg
  #shuffle things up one
  stdpr <- c(NA, stdpr[-length(stdpr)])
  spike <- prchg / stdpr
  return(spike)
}
myenv <- new.env()
# environment used to store tickers
tickers <- c("PBR", "AAPL", "MSFT", "GOOG")
getSymbols(tickers, env= myenv)
sp <-tickers['2013/2014']
asp <- augenSpike(as.vector(Cl(sp)))
sp$spike <- asp


## Create a vector of colors selected based on whether x is <0 or >0
## (FALSE + 1 -> 1 -> "blue";    TRUE + 1 -> 2 -> "red")
cols <- c("blue", "red" ) [(sp$spike > 0) +  1]

barplot(sp['2013-2014']$spike, col= cols, main="Augen Price Spike", xlab="Time Daily",ylab="Price Spike in Std Dev")
abline(h = 2, col = "red")
abline(h = 0, col = "black")
abline(h = -2, col = "red")

1 个答案:

答案 0 :(得分:0)

在提供的代码段中,sp为NA,导致Cl(sp)失败。原因是tickers仍然是字符串的向量,而不是表示股票代码的xts对象。由于使用自定义环境,xts对象无法访问。在没有该环境的情况下,将以库存符号命名的新变量添加到范围中。您可以创建xts对象的辅助向量,然后使用'2013/2014'下标。以下脚本应该执行您想要的操作:

library(quantmod)

slideapply <- function(x, n, FUN=sd) {
  v <- c(rep(NA, length(x)))
  for (i in n:length(x) ) {
    v[i] <- FUN(x[(i-n+1):i])
  } 
  return(v)   
}

augenSpike <- function(x, n=20) {
  prchg <- c(NA, diff(x))
  lgchg <- c(NA, diff(log(x)))
  stdevlgchg <- slideapply(lgchg, n, sd)
  stdpr <- x * stdevlgchg
  #shuffle things up one
  stdpr <- c(NA, stdpr[-length(stdpr)])
  spike <- prchg / stdpr
  return(spike)
}

tickers <- c("PBR", "AAPL", "MSFT", "GOOG")
getSymbols(tickers)
ticker_symbols <- c(PBR, AAPL, MSFT, GOOG)

sp <-ticker_symbols['2013/2014']
asp <- augenSpike(as.vector(Cl(sp)))
sp$spike <- asp


## Create a vector of colors selected based on whether x is <0 or >0
## (FALSE + 1 -> 1 -> "blue";    TRUE + 1 -> 2 -> "red")
cols <- c("blue", "red" ) [(sp$spike > 0) +  1]

barplot(sp['2013-2014']$spike, col= cols, main="Augen Price Spike", xlab="Time Daily",ylab="Price Spike in Std Dev")
abline(h = 2, col = "red")
abline(h = 0, col = "black")
abline(h = -2, col = "red")

产生这个可爱的图形:Output from R script