假设我有一个名为tlt的data.frame,其最后一行是:

           TLT.Open  TLT.Close 
2010-12-14     92.4      92.14   

我想添加一个名为tlt.barcolor的额外矢量,因此看起来像这样:

           TLT.Open  TLT.Close  TLT.BarColor
2010-12-14     92.4      92.14       "Green"

这是一个“打印”的功能,无论是绿色还是红色的吧台。

bar_color <- function(ticker) {

require("quantmod")

x <- getSymbols(ticker, auto.assign=FALSE)

open        <- x[,1]                       
close       <- x[,2]                       

last_open   <- tail(open,  n=1)            
last_close  <- tail(close, n=1)            



if       (last_open > last_close)    
           {print("Red Bar")} 

else if  (last_open < last_close)          
           {print("Green Bar")}   

 else       {print("Doji Bar")}    

您将使用什么R函数来发送输出以填充新向量?

super_dataframe <- cbind(TLT, apply(TLT, 1, valid_function))

该解决方案中的示例函数不起作用。但是,如果功能有效,则可以以这种方式附加输出。

有帮助吗?

解决方案

ticker 不能成为数据框架,但必须是角色。因此,使用应用程序来创建超级数据框架,您将遇到问题。以下功能为不同的签名提供了标签。

bar_color <- function(ticker){
   x <- getSymbols(ticker,auto.assign=FALSE)
   n <- nrow(x)
   switch(
      sign(x[n,1]-x[n,4])+2,
      "Green Bar",
      "Doji Bar",
      "Red Bar")
}

> TLT <- c("F","QQQQ")
> cbind(TLT,sapply(TLT,bar_color))
     TLT               
F    "F"    "Green Bar"
QQQQ "QQQQ" "Red Bar"  

如果您想要一个股票的标签,但日期不同,那么这就是您要寻找的:

bar_color <- function(ticker){
   x <- as.data.frame(getSymbols(ticker,auto.assign=FALSE))

   x$barcolor <- sapply(
            as.numeric(sign(x[,1]-x[,4])+2),
            function(j) switch(j,"Green Bar","Doji Bar","Red Bar")
   )

   return(x)
}

> head(bar_color("F"))
           F.Open F.High F.Low F.Close F.Volume F.Adjusted  barcolor
2007-01-03   7.56   7.67  7.44    7.51 78652200       7.51   Red Bar
2007-01-04   7.56   7.72  7.43    7.70 63454900       7.70 Green Bar
2007-01-05   7.72   7.75  7.57    7.62 40562100       7.62   Red Bar
2007-01-08   7.63   7.75  7.62    7.73 48938500       7.73 Green Bar
2007-01-09   7.75   7.86  7.73    7.79 56732200       7.79 Green Bar
2007-01-10   7.79   7.79  7.67    7.73 42397100       7.73   Red Bar

您的问题是,getSymbols不会返回您的数据框架,而是XTS对象。对于XTS,有特定的方法可以访问和添加数据,并且不应该期望这会像数据框架一样行事。

> X <- getSymbols("F",auto.assign=FALSE)
> class(X)
[1] "xts" "zoo"

其他提示

如果将“打印语句”更改为字符向量本身,例如“红色bar”,则可以将其添加到现有向量(例如最后一行)中。如果您将return()替换为print()s,则可能是更清晰的代码。唯一的问题是,向量需要处于所有相同的模式,因此您需要接受字符向量或使用一个行数据。

vec <- c(TLT[NROW(TLT), ] , bar.color( "TLT") )  # a character vector

onerowdf <- cbind( TLT[NROW(TLT), ], bar.color( "TLT")) ) 
# a data.frame (aka list)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top