2016-02-18 21 views
1

我有這個df(A)如何在約會對象轉換列的基礎上,指數

col1 col2 index 
    1 2  1 
    2 76  1 
    3 0  1 
    4 0  1 
    5 0  1 
    6 0  1 
    7 0  2 
    8 0  2 
    9 0  2 
    10 0  2 
    11 NA  2 
    12 NA  2 

我wolud喜歡的COL1轉換的時間序列,以年份和月份,3個月的時間間隔,基於在列索引,就像這樣:

  col1  col2  index 
     gen-1975 2   1 
     feb-1975 76  1 
     mar-1975 0   1 
     gen-1976 0   1 
     feb-1976 0   1 
     mar-1976 0   1 
     gen-1975 0   2 
     feb-1975 0   2 
     mar-1975 0   2 
     gen-1976 0   2 
     feb-1976 NA  2 
     mar-1976 NA  2 

我試着用tsas.Date,但我還沒有了預期的效果
預先感謝您。

回答

1

我假設三個月的間隔總是一月,二月,三月。您可以使用avedf拆分index值。對於每個唯一的index值,您首先會生成一個年的矢量,然後每年生成該年的三個月。代碼是這樣

# set start date for all sets of data 
    start_date <- as.Date("1975-01-01") 
# number of months in each year 
    num_months <- 3 
# generate col1 as R Date types 
    df$col1 <- as.Date(ave(df$col1, df$index, FUN=function(x) { yrs = seq.Date(start_date, length.out=length(x)/num_months, by="year") 
               sapply(yrs, function(y) seq.Date(y, length.out=num_months, by="month")) }), 
       origin=as.Date("1970-01-01")) 

如果你想在後面的代碼上使用df$col1這給了DF

  col1 col2 index 
1 1975-01-01 2  1 
2 1975-02-01 76  1 
3 1975-03-01 0  1 
4 1976-01-01 0  1 
5 1976-02-01 0  1 
6 1976-03-01 0  1 
7 1975-01-01 0  2 
8 1975-02-01 0  2 
9 1975-03-01 0  2 
10 1976-01-01 0  2 
11 1976-02-01 NA  2 
12 1976-03-01 NA  2 

,你可能要離開它的R Date類型以上。 但是,如果你想df$col1爲月 - 年格式的字符串,然後做

# convert col1 to character string using the month-year format 
     df <- cbind(col1=format(df$col1, "%b-%Y"), df[,-1]) 

這給

 col1 col2 index 
1 Jan-1975 2  1 
2 Feb-1975 76  1 
3 Mar-1975 0  1 
4 Jan-1976 0  1 
5 Feb-1976 0  1 
.... 
0

我們可以嘗試

library(data.table) 
setDT(df)[, col1:= as.character(col1) 
    ][,col1:= paste(c('gen', 'feb', 'mar'),rep(c(1975, 1976), 
       each=.N/2), sep='-'), index]