用变量名称模式重塑R中的形状 [英] Reshape in R with variable name patterns

查看:11
本文介绍了用变量名称模式重塑R中的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用基本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

感谢任何帮助。

推荐答案

您真的很接近,只需给Variable列出一个列表

 reshape(dfReshape3, dir='long', varying=list(c(3:5),c(6:8)), v.names=c('inc', 'ue'),times = c('80', '81', '82'))
     id sex time  inc ue
1.80  1   0   80 5000  0
2.80  2   1   80 2000  1
3.80  3   0   80 3000  0
1.81  1   0   81 5500  1
2.81  2   1   81 2200  0
3.81  3   0   81 2000  0
1.82  1   0   82 6000  0
2.82  2   1   82 3300  0
3.82  3   0   82 1000  1

这篇关于用变量名称模式重塑R中的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆