2017-02-20 65 views
0

利用發佈在論壇上的資源,我設法創建了一個腳本,將文件轉換爲xts類的對象。但是,這是這些對象的列表。最終,我想將這些文件轉換爲單獨的對象xts。我必須在腳本中輸入一個更改,它們作爲單獨的對象出現,每個對象都是xts類?拆分單獨對象中的xts列表

有腳本:

files <- list.files(pattern="*.mst") 
listmst <- vector("list", length(files)) 
names(listmst)<- files 
for (i in 1:length(files)) { 
    temp <- read.zoo(files[i], sep=",", header=TRUE, 
        index.column=1, format="%Y%m%d", tz="", 
        colClasses = rep(c("NULL","character", "numeric"), c(1,1,5))) 
    listmst[[files[i]]]<- as.xts(temp) 
} 
rm(temp,files) 

CSV文件等轉換: https://www.dropbox.com/s/paql3y0gm5gve3z/pourek.rar?dl=0

回答

0

你需要使用類似assign創建具有符號名稱的對象。例如:

files <- list.files(pattern = "*.mst") 
for (f in files) { 
    # Create symbol from file name 
    Symbol <- gsub("\\.mst", "", basename(f)) 
    # Ensure it's a valid R name 
    Symbol <- make.names(Symbol) 
    # Read data from file 
    temp <- read.zoo(f, sep=",", header=TRUE, format="%Y%m%d", tz="", 
        colClasses = rep(c("NULL","character", "numeric"), c(1,1,5))) 
    # Clean up column names 
    colnames(temp) <- gsub("^X\\.|\\.$", "", colnames(temp)) 
    # Create object named `symbol` containing data from `temp` 
    assign(Symbol, as.xts(temp)) 
} 
rm(Symbol, temp, f) 

現在,你應該在你的工作區中看到這一點:

R> ls() 
[1] "ABPL"  "AILLERON" "ALIOR"  "ALMA"  "ALTA"  
[6] "ALTERCO" "files"  "KREDYTIN" "KREZUS"  "KRKA"  
[11] "KRUK"  "KRUSZWICA" "MABION"  "MAKARONPL" "MANGATA" 
[16] "MARVIPOL" "MASTERPHA" "MBANK"  "MBWS"  "MCI"  
[21] "MCLOGIC" "MDIENERGIA" "MEDIACAP" "MEDIATEL" "X11BIT"  
[26] "X4FUNMEDIA" 
R> head(ABPL) 
      OPEN HIGH LOW CLOSE VOL 
2006-09-21 11.54 12.19 11.50 11.70 844641 
2006-09-22 11.69 11.69 11.25 11.60 53033 
2006-09-25 11.49 11.83 11.49 11.83 125607 
2006-09-26 11.90 12.05 11.90 12.04 104956 
2006-09-27 12.09 12.09 11.70 11.95 69062 
2006-09-28 11.70 12.00 11.65 12.00 37466 

注意,所有以數字開頭的符號,現在用「X」開頭,因爲[R對象下手一個數字不是「語法上有效的」。

+0

這正是我正在尋找的結果。在我完全理解代碼之前需要幾天時間。非常感謝 。 –