2013-04-15 69 views
0

我正在寫一個函數,該函數給出一個路徑將查找文件夾中的所有文件,並將所有csv讀入一個xts對象。這些文件都有相同的日期陣容,我希望每個文件都是xt中的另一列。我得到了以下功能,但是我得到了temp [,1]中的錯誤:不正確的維數。我究竟做錯了什麼?將時間序列合併爲一個文本文件

make.libor.xts <- function(folder){ 
    filenames <- list.files(path=folder, full.names=TRUE) 
    tables <- lapply(filenames, function(x){as.xts(read.zoo(x, sep=",", format="%Y-%m-%d", header=TRUE))}) 
    cnames <- lapply(filenames, function(x){basename(x)}) 
    myxts <- tables[1] 
    names(myxts) <- cnames[1] 
    if(length(filenames)>1){ 
    for(i in 2:length(filenames)){ 
     temp <- tables[i] 
     myxts$cnames[i] <- temp[,1] 
    } 
    } 
    return(myxts) 
} 
+1

我的猜測是你想要子括號的雙括號。例如'表[[1]]',而不是'表[1]' – GSee

+0

謝謝,幫助,現在它炸彈1:在myxts $ cnames [i] < - temp [,1]: 要替換的項目數一個替換長度的倍數,我認爲這個問題試圖動態地命名列即將添加 – postelrich

+0

是的,因爲這不是有效的語法。嘗試'cbind' – GSee

回答

1

您的代碼可以簡化一下,如下所示。使用Reduce函數在xts對象列表上調用merge.xts

dir("temp") 
## [1] "AAPL.csv" "IBM.csv" "MSFT.csv" 


READ.ALL.XTS <- function(folder) { 
    filenames <- list.files(path = folder, full.names = TRUE) 
    tables <- lapply(filenames, function(x) { 
     as.xts(read.zoo(x, sep = ",", format = "%Y-%m-%d", header = TRUE)) 
    }) 

    # Lets see contents of tables 
    cat("Calling from inside function begin...\n") 
    print(head(tables[[1]])) 
    print(head(tables[[2]])) 
    print(head(tables[[3]])) 
    cat("Calling from inside function end...\n") 
    cnames <- sapply(filenames, function(x) { 
     basename(x) 
    }) 
    combinedxts <- Reduce(f = merge.xts, tables) 
    names(combinedxts) <- cnames 
    return(combinedxts) 
} 

result <- READ.ALL.XTS("temp") 
## Calling from inside function begin... 
##    [,1] 
## 2013-01-03 542.10 
## 2013-01-04 527.00 
## 2013-01-07 523.90 
## 2013-01-08 525.31 
## 2013-01-09 517.10 
## 2013-01-10 523.51 
##    [,1] 
## 2013-01-03 195.27 
## 2013-01-04 193.99 
## 2013-01-07 193.14 
## 2013-01-08 192.87 
## 2013-01-09 192.32 
## 2013-01-10 192.88 
##    [,1] 
## 2013-01-03 27.25 
## 2013-01-04 26.74 
## 2013-01-07 26.69 
## 2013-01-08 26.55 
## 2013-01-09 26.70 
## 2013-01-10 26.46 
## Calling from inside function end... 


head(result) 
##   AAPL.csv IBM.csv MSFT.csv 
## 2013-01-03 542.10 195.27 27.25 
## 2013-01-04 527.00 193.99 26.74 
## 2013-01-07 523.90 193.14 26.69 
## 2013-01-08 525.31 192.87 26.55 
## 2013-01-09 517.10 192.32 26.70 
## 2013-01-10 523.51 192.88 26.46 
+0

將不會合並將它們全部合併成一列? – postelrich

+0

不..不適用於'xts'對象。 –

相關問題