I'm working on some World Bank panel data (with NA
values) that have the following structure:
df <- read.table(text="
Indicator Country 1996 1997 1998
X A v1 NA v3
X B v4 v5 v6
X C NA v8 v9
Y A z1 NA z3
Y B NA NA z6
Y C z7 z8 z9", header = TRUE)
And I look for obtaining this structure:
Country Year X Y
A 1996 v1 z1
A 1997 NA NA
A 1998 v3 z3
B 1996 v4 NA
B 1997 v5 NA
B 1998 v6 z6
C 1996 NA z7
C 1997 v8 z8
C 1998 v9 z9
I tried the answers given in Reshaping data.frame from wide to long format with the following code:
df.reshaped=reshape(df, direction="long", varying=list(names(df)[3:5]),
v.names=c("X", "Y"), idvar= "Country", times=1996:1998)
but don't get what I want. The real flat file contain almost 20 indicators * 214 Countries * 35 Years, so looking for your help.