You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用tidyr::spread()将两行数据合并为一行?参考资料未解决

解决tidyr::spread()处理选举数据的问题

嘿,我来帮你搞定这个tidyr::spread()的问题!看起来你想把按年份分行的选举得票数据,转成以年份为列的宽格式,对吧?先看看你的原始数据长什么样:

> df
# A tibble: 2 × 5
   Jaar Gemeente        GMcode Partij Aantal_stemmen
  <int> <chr>           <chr>  <chr>           <int>
1  2014 Stichtse Vecht GM1904 VVD              4347
2  2018 Stichtse Vecht GM1904 VVD                 0

要实现你想要的合并效果,只需要用spread()函数指定两个核心参数:

  • key:要转成列名的字段(这里是Jaar年份)
  • value:对应列要填充的数值(这里是Aantal_stemmen得票数)

其他列(Gemeente、GMcode、Partij)会自动作为行的唯一标识,因为它们在两行数据里是完全一致的。直接看代码:

library(tidyverse)

# 你的原始数据
df <- structure(list(Jaar = c(2014L, 2018L), Gemeente = c("Stichtse Vecht", "Stichtse Vecht"), GMcode = c("GM1904", "GM1904"), Partij = c("VVD", "VVD"), Aantal_stemmen = c(4347L, 0L)), .Names = c("Jaar", "Gemeente", "GMcode", "Partij", "Aantal_stemmen"), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"))

# 使用spread转换为宽格式
df_spread <- df %>%
  spread(key = Jaar, value = Aantal_stemmen)

# 查看转换后的结果
df_spread

运行后你会得到期望的合并结果:

> df_spread
# A tibble: 1 × 5
  Gemeente        GMcode Partij `2014` `2018`
  <chr>           <chr>  <chr>   <int>  <int>
1 Stichtse Vecht GM1904 VVD      4347      0

如果之后你的数据里加入了更多政党或市政,这个方法依然适用——spread()会自动按所有非key/value的列分组,保证每个唯一的市政-政党组合对应一行数据。

内容的提问来源于stack exchange,提问作者Tdebeus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:40:49