摸索出一个方法
> rm(list=ls())
>
> wide <- data.frame(id = rep(1:8),
+ x1990 = round(rnorm(4),2),
+ x2000 = round(rnorm(4),2),
+ y1990 = round(runif(4),2),
+ y2000 = round(runif(4),2),
+ age=seq(from = 35, to = 70, by = 5))
> wide
id x1990 x2000 y1990 y2000 age
1 1 -1.59 -1.37 0.57 0.70 35
2 2 -0.30 0.38 0.40 0.67 40
3 3 0.74 0.36 0.98 0.53 45
4 4 -0.29 0.02 0.80 0.84 50
5 5 -1.59 -1.37 0.57 0.70 55
6 6 -0.30 0.38 0.40 0.67 60
7 7 0.74 0.36 0.98 0.53 65
8 8 -0.29 0.02 0.80 0.84 70
>
> long <- reshape(wide, idvar = "id",
+ varying = c("x1990", "x2000", "y1990", "y2000"),
+ timevar = "year",
+ times = c(1990, 2000),
+ v.names = c("x", "y"),
+ direction = "long")
> long
id age year x y
1.1990 1 35 1990 -1.59 -1.37
2.1990 2 40 1990 -0.30 0.38
3.1990 3 45 1990 0.74 0.36
4.1990 4 50 1990 -0.29 0.02
5.1990 5 55 1990 -1.59 -1.37
6.1990 6 60 1990 -0.30 0.38
7.1990 7 65 1990 0.74 0.36
8.1990 8 70 1990 -0.29 0.02
1.2000 1 35 2000 0.57 0.70
2.2000 2 40 2000 0.40 0.67
3.2000 3 45 2000 0.98 0.53
4.2000 4 50 2000 0.80 0.84
5.2000 5 55 2000 0.57 0.70
6.2000 6 60 2000 0.40 0.67
7.2000 7 65 2000 0.98 0.53
8.2000 8 70 2000 0.80 0.84