什么 R 函数将输出发送到新向量?
假设我有一个名为 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 函数来发送输出以填充新向量,而不是使用 print() R 函数(仅打印到控制台)?
super_dataframe <- cbind(TLT, apply(TLT, 1, valid_function))
示例函数在此解决方案中不起作用。但如果该函数有效,则可以通过这种方式附加它的输出。
Suppose I have a data.frame named TLT whose last line is this:
TLT.Open TLT.Close
2010-12-14 92.4 92.14
And I want to add an extra vector called TLT.BarColor so it looks like this:
TLT.Open TLT.Close TLT.BarColor
2010-12-14 92.4 92.14 "Green"
Here is a function that "prints" whether it was a green or red bar day.
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")}
Instead of using the print() R function (which only prints to console), what R function would you use to send the output to populate a new vector?
super_dataframe <- cbind(TLT, apply(TLT, 1, valid_function))
The sample function does not work in this solution. But if the function were valid, it's output could be attached in this manner.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您将打印语句更改为简单的字符向量本身,例如“Red Bar”,您可以将其添加到现有向量(例如最后一行)。如果用 return() 代替 print(),代码可能会更清晰。唯一的问题是向量需要具有相同的模式,因此您需要接受字符向量或使用单行 data.frame。
If you changed the print statements to simply the character vector itself, e.g."Red Bar", you can add that to an existing vector such as the last row. It might be clearer code if you substituted return() for the print()'s. The only problem is that a vector needs to be of all the same mode so you would need to accept a character vector or use a one line data.frame.
ticker
不能是数据框,但必须是字符。因此,使用您用来创建超级数据框的应用程序时,您会遇到问题。以下函数给出了不同代码的标签。如果您想要一个股票但不同日期的标签,那么这就是您正在寻找的:
您可能面临的问题是 getSymbols 不会返回数据帧,而是返回 xts 对象。对于 xts,有特定的方法来访问和添加数据,并且不应期望它的行为类似于数据框。
ticker
can't be a dataframe, but has to be a character. So with the apply you use to create your super data frame, you'll have a problem. THe following function gives the labels for different tickers.If you want the labels for one ticker but different dates, then this is what you're looking for :
The problem you -likely- face is the fact that getSymbols does not return you a dataframe, but an xts object. For xts there are specific methods to access and add data, and one should not expect this to behave like a data frame.