在R中顺序合并循环

时间:2014-01-31 10:53:30

标签: r merge quandl

我正在使用Quandl的R-package尝试创建一个包含指定公司列表的股票报价的数据框。

install.packages("Quandl")

library(Quandl)
library(reshape)

Quandl.auth("yourauthenticationtoken")

#create date structure (using AAPL)
structure <- Quandl("GOOG/NASDAQ_AAPL",start_date="2004-01-01",end_date="2013-12-31", collapse="weekly")[c(1)]

#list of stocks to fetch
stocks <- c("MSFT", "AAPL")

# Function to fetch stock quotes
rdQcurr <- function(curr){
    codes <- paste("GOOG/NASDAQ_",curr,sep="")
    for(i in 1:length(stocks)){
    df<-Quandl(codes[i],start_date="2004-01-01",end_date="2013-12-31", collapse="weekly")[c(1,2)]

    #rename coloumn 2 to the name of the stock 
    names(df)[2]<-paste(stocks[i])
    #merge i'th stock to structure data frame 
    structure <- merge(x=structure, y=df, by = "Date", all.x=TRUE)
}
} 

quotes <- rdQcurr(stocks) 

编辑:此代码确实运行,但数据框“引号”为NULL。

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:3)

请通过R

的基础知识
rdQcurr <- function(curr){
    codes <- paste("GOOG/NASDAQ_",curr,sep="")
    for(i in 1:length(stocks)){
    df<-Quandl(codes[i],start_date="2004-01-01",end_date="2013-12-31", collapse="weekly")[c(1,2)]

    #rename coloumn 2 to the name of the stock 
    names(df)[2]<-paste(stocks[i])
    #merge i'th stock to structure data frame 
    structure <- merge(x=structure, y=df, by = "Date", all.x=TRUE)
}
 return(structure)
} 
> quotes <- rdQcurr(stocks) 
> quotes
          Date  MSFT
1   2004-01-04 27.58
2   2004-01-11 28.03
3   2004-01-18 27.72
4   2004-01-25 28.26
5   2004-02-01 27.84
---------------------