Excel or R: Preparing time series from multiple sources?

前端 未结 2 1896
野性不改
野性不改 2020-12-31 20:33

Lately I often had to handle time series data from multiple .csv sources in the same analysis. Let\'s assume for simplicity that all series are regular quarterly series (no

2条回答
  •  Happy的楠姐
    2020-12-31 21:37

    I do this in R all the time. You may find it easier to do in Excel but if your data change, you have to do the same process again. Using R makes it much easier to update and reproduce your results.

    Dealing with monthly or quarterly frequencies are made significantly easier with zoo's yearmon and yearqtr index classes, respectively. Once you have your data in zoo objects with yearqtr indexes, all you have to do is merge all the objects.

    Here's your sample data:

    Lines1 <-
    "27.05.11;5965.95
    26.05.11;5947.06
    25.05.11;5942.82
    24.05.11;5939.98"
    f1 <- read.csv2(con <- textConnection(Lines1), header=FALSE)
    close(con)
    
    Lines2 <-
    "Germany;Switzerland;USA;OECDEurope
    69,90974;61,8241;55,60966;64,96157
    67,0394;62,18966;56,47361;64,15152
    70,56651;63,6347;56,87237;65,43568"
    f2 <- read.csv2(con <- textConnection(Lines2), header=TRUE)
    close(con)
    
    Lines3 <-
    "1984-04-01,33.3238396624473
    1984-07-01,63.579833082501
    1984-10-01,35.8375401560349"
    f3 <- read.csv(con <- textConnection(Lines3), header=FALSE)
    close(con)
    

    The example below assumes the starting date for the first file is 1984Q2 and the starting date for the second file is 1984Q4. You can see that merge.zoo takes care of aligning all the dates for you. After everything is aligned in your zoo object, you can use the as.ts method to create a mts object.

    z1 <- zoo(f1[,-1], as.Date(f1[,1], "%d.%m.%y"))
    z2 <- zoo(f2, as.yearqtr("1984Q4")+(seq_len(NROW(f1))-1)/4)
    z3 <- zoo(f3[,-1], as.yearqtr(as.Date(f3[,1])))
    
    library(xts)
    # Use xts::apply.quarterly to aggregate series with higher periodicity.
    # Here I just take the last obs but you could use another function (e.g. mean).
    z1 <- apply.quarterly(z1, last)
    index(z1) <- as.yearqtr(index(z1))  # convert the index to yearqtr
    
    (Z <- merge(z1,z2,z3))
    #         z1      Germany  Switzerland USA      OECDEurope z3
    # 1984 Q2                              33.32383
    # 1984 Q3                              63.57983
    # 1984 Q4     69.90974 61.8241     55.60966 64.96157   35.83754
    # 1985 Q1     67.0394  62.18966    56.47361 64.15152   
    # 1985 Q2     70.56651 63.6347     56.87237 65.43568   
    # 1985 Q3     69.90974 61.8241     55.60966 64.96157   
    # 2011 Q2 5965.95                          
    
    # Note that ts will create an object with a observation for every period,
    # even if all the columns are missing.
    TS <- as.ts(Z)
    

提交回复
热议问题