r - 使用嵌入的列和年份名称进行整形
问题描述
嗨,我有一个数据,其中年份值嵌入列名中,如下所示,我想将其重塑为长格式。
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
其他州也类似有什么想法吗?非常感谢!
解决方案
使用rename
和的解决方案gather
df %>%
rename_all(.funs = funs(gsub('POPEST', '', .))) %>%
gather(year, POPEST, -state, -city)
推荐阅读
- postgresql - PostrgreSql 数据库写/读统计
- excel - 使用excel在Word文档中添加表格
- bootstrap-4 - Bootstrap4 手风琴不工作。请检查我的代码
- java - FreeMarker 模板错误:JSONArray 包装到 febStringModel
- c++ - 无法在头文件中包含标头,但可以包含在 cpp 中
- r - 在 stargazer 中混合和匹配来自 multinom 模型的协变量
- postgresql - postgres 的默认密码
- angular - Angular如何正确获取类元素?
- python - 分配变量 Python 时出现语法错误
- css - 全局导入 scss 变量,可用于所有角度组件