【发布时间】:2013-02-03 13:33:53
【问题描述】:
我正在尝试使用 base R 的 reshape 函数在 Stata 中重现 reshape 的结果。
状态
webuse reshape3, clear
li, clean
// reshape long
reshape long inc@r ue, i(id) j(year)
list, sepby(id) clean
这会在reshape: 之前产生:
. li, clean
id sex inc80r inc81r inc82r ue80 ue81 ue82
1. 1 0 5000 5500 6000 0 1 0
2. 2 1 2000 2200 3300 1 0 0
3. 3 0 3000 2000 1000 0 0 1
注意存根inc 的名称模式。在reshape 之后,我得到:
. list, sepby(id) clean
id year sex incr ue
1. 1 80 0 5000 0
2. 1 81 0 5500 1
3. 1 82 0 6000 0
4. 2 80 1 2000 1
5. 2 81 1 2200 0
6. 2 82 1 3300 0
7. 3 80 0 3000 0
8. 3 81 0 2000 0
9. 3 82 0 1000 1
R
我在 R 中遇到了麻烦,因为我不知道如何指定解析宽格式变量名所需的正则表达式。
library(foreign)
dfReshape3 <- read.dta('http://www.stata-press.com/data/r12/reshape3.dta')
reshape(dfReshape3, dir='long', varying=3:8, v.names=c('inc', 'ue'),
times = c('80', '81', '82'))
但是,这给了我:
id sex time inc ue
1.80 1 0 80 5000 5500
2.80 2 1 80 2000 2200
3.80 3 0 80 3000 2000
1.81 1 0 81 6000 0
2.81 2 1 81 3300 1
3.81 3 0 81 1000 0
1.82 1 0 82 1 0
2.82 2 1 82 0 0
3.82 3 0 82 0 1
任何帮助表示赞赏。
【问题讨论】:
-
read.dta 是什么?使用 base R 时它不起作用。
-
@arun 道歉。
library(foreign). -
一个非常简单的解决方案是从“inc[0-9]+r”变量中删除尾随的“r”。
names(dfReshape3) <- gsub("r$", "", names(dfReshape3))。然后重塑非常简单:reshape(dfReshape3, dir='long', varying=3:8, sep = "")