这是一个使用 tidyverse 的解决方案。首先,我们将数据收集成窄格式的整洁数据,然后将其展开回宽格式,通过将第一列从gather() 中排除,将第一列设置为收集观察的键。
我们将使用来自U.S. Census Bureau 的州级摘要数据来演示该技术。
我为四个州创建了一个人口数据表,其中州(观察)在列中,变量在表的行中列出。
为了使示例可重现,我们将数据输入 Excel 并将其保存为逗号分隔值文件,我们将其分配给 R 中的向量并使用read.csv() 读取。
textFile <- "Variable,Georgia,California,Alaska,Alabama
population2018Estimate,10519475,39557045,737438,4887871
population2010EstimatedBase,9688709,37254523,710249,4780138
pctChange2010to2018,8.6,6.2,3.8,2.3
population2010Census,8676653,37253956,710231,4779736"
# load tidyverse libraries
library(tidyr)
library(dplyr)
# first gather to narrow format then spread back to wide format
data %>%
gather(.,state,value,-Variable) %>% spread(Variable,value)
...和结果:
state pctChange2010to2018 population2010Census
1 Alabama 2.3 4779736
2 Alaska 3.8 710231
3 California 6.2 37253956
4 Georgia 8.6 8676653
population2010EstimatedBase population2018Estimate
1 4780138 4887871
2 710249 737438
3 37254523 39557045
4 9688709 10519475