reshaping time series data in R -
i have quarterly time series economic data imf ifs need long form.
right now, rows variables per country , columns time, looks 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 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 find advice on using reshape when id variable , measurement variables both in rows.
it partial melt
followed dcast
in 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
Comments
Post a Comment