首页 > 解决方案 > 使用嵌入的列和年份名称进行整形

问题描述

嗨,我有一个数据,其中年份值嵌入列名中,如下所示,我想将其重塑为长格式。

state<- c('MN', 'PA', 'NY')
city<-  c('Minessota', 'Pittsburgh','Newyork')
POPEST2010<- c(2899, 344,4555)
POPEST2011<- c(4444, 348,8999)
POPEST2012<- c(555, 55,77665)
df<- data.frame(state,city,  POPEST2010, POPEST2011, POPEST2012)

关于如何重塑为长格式的任何建议,以便我可以看到如下数据:

state  city           year POPEST
MN     Minessota      2010  2899
MN     Minessota      2011  4444
MN     Minessota      2012  8999

其他州也类似有什么想法吗?非常感谢!

标签: rdplyrreshapereshape2

解决方案


使用rename和的解决方案gather

 df %>%
 rename_all(.funs = funs(gsub('POPEST', '', .))) %>%
 gather(year, POPEST, -state, -city)

推荐阅读