2017-02-03 60 views
1

我想從許多公司使用R的包「quantmod」獲取Google財務狀況的財務信息。我在列表中獲得滿意的結果,但我想將其導出到Excel文件中。爲每個列表成員使用不同的電子表格,並且所述表格的名稱是列表中的名稱。到目前爲止,我有這樣的代碼和輸出:導出列表從R到Excel,同時保持列表名稱和子列表名稱

library(quantmod) 
library(dplyr) 
library(tidyr) 
symbols <- stockSymbols()[,1:2] 
allfunc<-function(y) sapply(fin1, function(x) x$IS$A[y, ],USE.NAMES = TRUE)*10^6 
s <- c("AAPL","GOOG","IBM","GS","AMZN","GE") 
want<-c("Total Revenue","Operating Income") 
fin1 <- lapply(s, getFinancials, auto.assign=FALSE,names=s) 
names(fin1)<-s 
all<- lapply(want,allfunc) 
ss<-sapply(want,allfunc) 
names(all)<-want 
all 

和輸出「所有」是:

$`Total Revenue` 
        AAPL  GOOG  IBM   GS  AMZN   GE 
2016-09-24 2.15639e+11 9.0272e+10 7.9919e+10 3.7712e+10 1.35987e+11 1.23693e+11 
2015-09-26 2.33715e+11 7.4989e+10 8.1741e+10 3.9395e+10 1.07006e+11 1.17385e+11 
2014-09-27 1.82795e+11 6.6001e+10 9.2793e+10 4.0085e+10 8.89880e+10 1.17184e+11 
2013-09-28 1.70910e+11 5.5519e+10 9.8367e+10 4.0874e+10 7.44520e+10 1.13244e+11 

$`Operating Income` 

       AAPL  GOOG  IBM   GS  AMZN   GE 
2016-09-24 6.0024e+10 2.3716e+10 1.0699e+10 1.0304e+10 4.186e+09 9.0300e+09 
2015-09-26 7.1230e+10 1.9360e+10 1.5262e+10 8.7780e+09 2.233e+09 9.3470e+09 
2014-09-27 5.2503e+10 1.6496e+10 1.9244e+10 1.2357e+10 1.780e+08 1.1348e+10 
2013-09-28 4.8999e+10 1.5403e+10 1.9422e+10 1.1737e+10 7.450e+08 9.9490e+09 

我想有兩片「收入」,「營業外收入」在XLSX,同時保持rownames和欄目名稱。但我無法找到一個辦法去做清單。 請幫助

回答

1

事情是這樣的:

library(xlsx) 

wb = createWorkbook() # Create an Excel workbook object 

lapply(names(all), function(s) { 
    sht = createSheet(wb, s)  # Add a sheet to the workbook using the name of the list element we want to save 
    addDataFrame(all[[s]], sht)  # Add the list element (i.e., the data frame) to the current worksheet 
} 

saveWorkbook(wb, "my_workbook.xlsx") # Save the workbook as a Excel file