简体   繁体   中英

reshaping time series data in R

I have quarterly time series economic data from the IMF IFS that I need to get into long form.

Right now, the rows are variables per country and the columns are time, so it looks something like this.

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

I need to get it into long form:

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

I haven't been able to find any advice on using reshape when the ID variable and the measurement variables are both in rows.

It is a partial melt followed by a dcast in the reshape2 package:

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)]

Gives:

> 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

Base R method using stack and reshape , using the below data.frame

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

Reshape away:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM