楼主: 蓝色
7591 12

[学习分享] R怎么能把wide的数据变成long的数据【已经解决】 [推广有奖]

11
蓝色 发表于 2015-2-17 19:17:29
  1. rm(list=ls())

  2. wide <- data.frame(id  = rep(1:8),
  3.                    x1990 = round(rnorm(4),2),
  4.                    x2000 = round(rnorm(4),2),
  5.                    y1990 = round(runif(4),2),
  6.                    y2000 = round(runif(4),2),
  7.                    age=seq(from = 35, to = 70, by = 5))
  8. wide

  9. long <- reshape(wide, idvar = "id",
  10.                 varying = c("x1990", "x2000", "y1990", "y2000"),
  11.                 timevar = "year",
  12.                 times = c(1990, 2000),
  13.                 v.names = c("x", "y"),
  14.                 direction = "long")
  15. long
复制代码
摸索出一个方法


> 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

12
李会超 发表于 2015-2-26 14:53:28
本人觉得reshape包里面的函数比reshape函数更方便……

13
蓝色 发表于 2015-2-26 15:05:59
李会超 发表于 2015-2-26 14:53
本人觉得reshape包里面的函数比reshape函数更方便……
reshape包的命令我没有试不出来
R的帮助文件不好用,介绍的太简单

相比Stata的manual清晰多了,而且reshape命令更加省事

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2025-12-28 17:01