2012-02-16 47 views
0

我在45年的時間跨度內提取每日溫度數據。我使用了所有可能的方法來追加,cbind,將這些數據轉化爲每年循環增長的變量。 除了價值我還包括時間(as.Date)。不幸的是,我最後的變量由45行和2列組成,每個單元格包含值(左列)和日期(右列)。但是,我無法找到一種方法來「擴大」單元格,以獲得每個單元格包含一個值的兩列。將矩陣中的幾個列表對象轉換爲實際列表

起初我試圖從合併(,by ='date')循環中得到一個更好的變量,但它不工作,因爲我只有一年的日期。 我正在尋找擴展單元格的命令,或者甚至更好,它將真正將循環內部的變量底部的兩列(值爲& date)附加爲每個單元格的單個條目。

輸入數據是帶年份的文本文件(寫有1960年的前導行,以及31 x 13矩陣)被寫在彼此之下。 -9999是我的NA標誌。

1960 - - - - - - - - - - - - 
1 -22.2 -13.5 -6.2 -5.4 . . . x(1,13) 
2 -22.4 -15.9 -5.7 7.6 . . . x(2,13) 
    . 
    . 
    . 
31 
30 -9.9 -9999 -8 4.8 . . . x(30,13) 
31 -17 -9999 -6.2  . . . x(31,13) 
1961 - - - - - - - - - - - - 
1 -17.8 -22.6 -11.7 -0.5 4 11.9 10.4 14.8 12 -0.1 -9.2 -16.3 

代碼簡化:

dat1 <- data.frame(read.table(filename)) 
dat1$NUM <- 1:length(dat1$V1) #I needed an index 
TYs <- 1960 # Year start 
TYe <- 2005 # Year end 
TYi–TYs 
TMP3 <- NULL #The variable that should store the data. Append new data every loop 

while (TYi <= TYe){ 
    index <- dat1$NUM[dat1$V1==TYi] 

    # get the start and stop of matrix indices 
    begin <- index+1 
    end <- begin+30 
    oddyear <-format(as.Date(paste('3112',TYi),'%d%m%Y'),'%j')== '366' #checks if TYi is oddyear 
    if (oddyear==TRUE){ 
     date <- seq(as.Date(paste('0101',TYi), '%d%m%Y'),as.Date(paste('3112',TYi), '%d%m%Y'),'day') 
     TMP2 <- NULL 
     TMP2$data[1:31] <- TMP[1:31] 
     TMP2$data[32:60] <- TMP[32:60] 
#... 
     TMP2$data[336:366] <- TMP[342:372] 
     TMP2$date <- date 
     TMP3 <- rbind(TMP3, TMP2) 
     TYi <- TYi+1 
     TMP2 <- NULL 
     TMP <- NULL 
       } else { # similar with one day less for non-oddyears 
} 

這就是我得到年底TMP3:

data   date  
TMP2 Character,366 Numeric,366 
TMP2 Character,365 Numeric,365 
TMP2 Character,365 Numeric,365 

我想是這樣的:

data   date  
-22.2 1960-01-01 
-22.4 1960-02-01 
... 

乾杯, 埃裏克

+7

你能告訴我們:你的初始數據是什麼樣的;你正在使用的代碼;以及您的數據所需的最終格式?就目前而言......我不知道你做了什麼,或者你是怎麼做到的,或者爲什麼它錯了! – Justin 2012-02-16 23:07:39

回答

0

Eric, 我同意賈斯丁的觀點,即使沒有可重複的樣本,也很難給出正確答案。但是,如果涉及時間序列,我會建議使用xts包。

require('xts') 
result<-xts(12.22,order.by=as.POSIXct(paste('1990','-','01','-','01',sep=''))) 

進行連結使用下列內容:

result<-rbind(result,xts(11.22,order.by=as.POSIXct(paste('1991','-','01','-','01',sep='')))) 

你應該得到:

1990-01-01 12.22 
1991-01-01 11.22 
0

它的工作原理。我甚至找到了我打算使用的命令(unlist())。

result <- xts(as.numeric(unlist(XX[,1])), order.by=as.Date(unlist(XX[,2]))) 

我的結果(XX)中的條目是矩陣內的列表。通過將unlist()與xts()結合使用,它可以很好地工作。

非常感謝。

埃裏克