【问题标题】:Reshape in R with variable name patterns使用变量名称模式在 R 中重塑
【发布时间】: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) &lt;- gsub("r$", "", names(dfReshape3))。然后重塑非常简单:reshape(dfReshape3, dir='long', varying=3:8, sep = "")

标签: r stata reshape


【解决方案1】:

你真的很亲密,只是给不同的列表

 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

【讨论】:

  • 有没有办法以更通用的方式创建选项times?意思不是硬编码数字c('80', '81', '82'),而是直接从数据中恢复它们?谢谢!
  • @ÁlvaroA.GutiérrezVargas 您可以使用正则表达式从数据集名称中提取数字。即:unique(stringr::str_extract(nn,"\\d+"))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
  • 2018-10-10
  • 2014-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多