2013-04-15 1 views
0

경로를 지정하면 폴더의 모든 파일을 찾고 모든 CSV를 하나의 xts 객체로 읽는 함수를 작성합니다. 파일은 모두 같은 날짜의 라인업을 가지고 있으며 각 파일을 xts의 다른 열로 만들려고합니다. 다음과 같은 함수가 있지만 temp [1]에 오류가 있습니다. 치수가 잘못되었습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?시계열을 하나의 xts로 결합하십시오.

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]'이 아니고 – GSee

+0

덕분에 도움이되었습니다. 1 : myxts에서 $ cnames [i] <- temp [, 1] : 대체 할 항목 수가 없습니다. 대체 길이의 배수로,이 문제는 유효한 문법이 아니기 때문에, – postelrich

+0

을 추가하는 칼럼에 동적으로 이름을 붙이려고하고 있다고 생각합니다. Try'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'개체가 아닙니다. –