我需要一些关于R的quantmod包和与for循环的交互方面的帮助。我有向量year
library(quantmod)
getFinancials("GE")
year <- colnames(viewFin(GE.f, "IS", "A"))
year
# [1] "2015-12-31" "2014-12-31" "2013-12-31" "2012-12-31"viewFin函数为我提供了以下输出:
viewFin(GE.f, type="IS", period="A")["Net Income", year[1]]
# Annual Income Statement for GE
# [1] -6126但是,如果我试图通过对年份进行索引来循环,则会得到以下错误:
> for(x in 1:4){
+ (viewFin(GE.f, type="IS", period="A")["Net Income", year[x]])
+ x=x+1
+ }
Annual Income Statement for GE
Annual Income Statement for GE
Annual Income Statement for GE
Annual Income Statement for GE
Error in viewFin(GE.f, type = "IS", period = "A")["Net Income", year[x]] :
subscript out of bounds我的想法是让日期、财务名称(净收入、股本等)和符号创建一个数据框架,将公司分成行和年&财务作为列。
viewFin函数是否阻塞到x值的条目?
发布于 2017-02-05 16:35:06
请注意,您不能在R.中的for循环中更改迭代器,因此在for循环末尾的x = x + 1是不必要的,并且被忽略了。还请注意,在for循环中禁用了自动打印,因此需要显式调用print。您可以做的另一件事是直接迭代一个向量(不需要子集)。所以for循环可能如下所示:
for(y in year) {
print(viewFin(GE.f, type="IS", period="A")["Net Income", y])
}也就是说,for循环是不必要的。您可以直接使用子设置获得相同的结果。
netIncome <- viewFin(GE.f, type="IS", period="A")["Net Income",]使用符号作为行,以行项和日期作为列的data.frame可能会有问题,因为没有理由每个符号应该具有相同的数据年数,或者完全相同的行项。最好先将所有数据以长格式放置,直到您知道正在使用的是什么。这是一个用于多个符号的函数。
stackFinancials <-
function(symbols, type = c("BS", "IS", "CF"), period = c("A", "Q")) {
type <- match.arg(toupper(type[1]), c("BS", "IS", "CF"))
period <- match.arg(toupper(period[1]), c("A", "Q"))
getOne <- function(symbol, type, period) {
gf <- getFinancials(symbol, auto.assign = FALSE)
vf <- viewFinancials(gf, type = type, period = period)
df <- data.frame(vf, line.item = rownames(vf), type = type, period = period,
symbol = symbol, stringsAsFactors = FALSE, check.names = FALSE)
long <- reshape(df, direction="long", varying=seq(ncol(vf)), v.names="value",
idvar="line.item", times=colnames(vf))
rownames(long) <- NULL
long
}
# combine all into one data.frame
do.call(rbind, lapply(symbols, getOne, type = type, period = period))
}下面是一个使用它的例子:
R> Data <- stackFinancials(c("GE", "AAPL"), type = "IS", period = "A")
Annual Income Statement for GE
Annual Income Statement for AAPL
R> head(Data)
line.item type period symbol time value
1 Revenue IS A GE 2016-12-31 123693
2 Other Revenue, Total IS A GE 2016-12-31 NA
3 Total Revenue IS A GE 2016-12-31 123693
4 Cost of Revenue, Total IS A GE 2016-12-31 92508
5 Gross Profit IS A GE 2016-12-31 31185
6 Selling/General/Admin. Expenses, Total IS A GE 2016-12-31 18377
R> tail(Data)
line.item type period symbol time value
387 Effect of Special Items on Income Taxes IS A AAPL 2013-09-28 NA
388 Income Taxes Ex. Impact of Special Items IS A AAPL 2013-09-28 NA
389 Normalized Income After Taxes IS A AAPL 2013-09-28 NA
390 Normalized Income Avail to Common IS A AAPL 2013-09-28 NA
391 Basic Normalized EPS IS A AAPL 2013-09-28 NA
392 Diluted Normalized EPS IS A AAPL 2013-09-28 5.68https://stackoverflow.com/questions/42047746
复制相似问题