在R中重塑时间序列数据
我有来自国际货币基金组织IFS的季度时间序列经济数据,我需要把这些数据整理成长期数据 现在,行是每个国家的变量,列是时间,所以看起来像这样在R中重塑时间序列数据,r,panel-data,R,Panel Data,我有来自国际货币基金组织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 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
,然后是deformate2
包中的dcast
:
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
基本R方法使用
堆栈
和重塑
,使用下面的数据。帧
d <- data.frame(country = c("USA","USA","UK","UK"), variable = c("inflation","GDPPC","inflation","GDPPC"),Q1=1:4,Q2=5:8)
d
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