簡體   English   中英

重塑R中的時間序列數據

[英]reshaping time series data in R

我需要獲取IMF IFS的季度時間序列經濟數據,我需要對此進行詳細表述。

現在,行是每個國家/地區的變量,列是時間,所以看起來像這樣。

     country  variable    Q1  Q2 
[1,] "USA"   "inflation" "1" "5"
[2,] "USA"   "GDPPC"     "2" "6"
[3,] "UK"    "inflation" "3" "7"
[4,] "UK"    "GDPPC"     "4" "8"

我需要把它變成長形:

    country  Time  inflation    GDPPC
[1,] "USA"   "Q1" "1"          "2"  
[2,] "USA"   "Q2" "5"          "6"  
[3,] "UK"    "Q1" "3"          "4"  
[4,] "UK"    "Q2" "7"          "8" 

當ID變量和測量變量都位於行中時,我無法找到有關使用重塑的任何建議。

它是一個局部的melt ,接着通過一個dcastreshape2包:

d = data.table(country = c("USA","USA","UK","UK"), variable = c("inflation","GDPPC","inflation","GDPPC"),Q1=as.character(1:4),Q2=as.character(5:8))
require(reshape2)
d2 = melt(d, id=c("country", "variable"))
colnames(d2)[3] = "Time" 
rr=dcast(d2, country +Time ~ variable)
rr = rr[order(rr$country,decreasing=T),c(1:2,4,3)]

得到:

> rr
  country Time inflation GDPPC
3     USA   Q1         1     2
4     USA   Q2         5     6
1      UK   Q1         3     4
2      UK   Q2         7     8

使用stackreshape Base R方法,使用以下data.frame

d <- data.frame(country = c("USA","USA","UK","UK"), variable = c("inflation","GDPPC","inflation","GDPPC"),Q1=1:4,Q2=5:8)

重塑:

intm <- data.frame(d[,c("country","variable")],stack(d[,c("Q1","Q2")]))
reshape(intm, idvar=c("country","ind"), timevar="variable", direction="wide")

#  country ind values.inflation values.GDPPC
#1     USA  Q1                1            2
#3      UK  Q1                3            4
#5     USA  Q2                5            6
#7      UK  Q2                7            8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM