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

如何将投票数据拆分转多列:提取各城市得票前两名政党信息

解决土耳其城市投票数据的政党排名列转换问题

问题背景

处理2019年土耳其大城市投票数据集d_Buyuksehir_2019,需要提取每个城市得票最高的两个政党,将数据转换为包含first_party、first_votes、second_party、second_votes的宽表结构。尝试使用group_by()+top_n()分组切片后无法完成最终的列转换。

原始数据结构

# 原始数据预览
d_Buyuksehir_2019 %>% head(10)

对应数据:

noilpartyvotes
1AdanaCHP656704
1AdanaMHP523751
2AnkaraCHP1662209
2AnkaraAK PARTİ1538410
3AntalyaCHP714302
3AntalyaAK PARTİ652882
4AydinCHP368791
4AydinAK PARTİ299056
5Balikesi̇rAK PARTİ375539
5Balikesi̇rİYİ PARTİ365333

期望输出结构

example <- data.frame(
    city = c("Adana","Ankara","Antalya","Balikesir"),
    first_party = c("chp", "chp", "chp", "akp"),
    first_votes = c(656704,1662209,714302,375539),
    second_party = c("mhp","akp","akp","iyi"),
    second_votes = c(523751,1538410,652882,365333)
)
example

输出样式:

cityfirst_partyfirst_votessecond_partysecond_votes
Adanachp656704mhp523751
Ankarachp1662209akp1538410
Antalyachp714302akp652882
Balikesirakp375539iyi365333

解决方案

使用dplyr结合tidyr的pivot_wider函数完成转换,步骤如下:

  1. 按城市分组,对每个城市的票数降序排序
  2. 为每个城市内的政党添加排名(1为最高票,2为次高票)
  3. 将长表转为宽表,匹配排名对应的政党和票数
  4. 整理列名并格式化政党名称(可选)

完整代码

library(dplyr)
library(tidyr)

result <- d_Buyuksehir_2019 %>%
  # 按城市分组,降序排列票数
  group_by(il) %>%
  arrange(desc(votes), .by_group = TRUE) %>%
  # 取前2名政党
  slice(1:2) %>%
  # 添加排名列
  mutate(rank = row_number()) %>%
  # 转换为宽表
  pivot_wider(
    names_from = rank,
    values_from = c(party, votes),
    names_sep = "_"
  ) %>%
  # 重命名列并格式化政党名称为小写缩写
  rename(
    city = il,
    first_party = party_1,
    first_votes = votes_1,
    second_party = party_2,
    second_votes = votes_2
  ) %>%
  mutate(
    first_party = case_when(
      first_party == "CHP" ~ "chp",
      first_party == "AK PARTİ" ~ "akp",
      first_party == "MHP" ~ "mhp",
      first_party == "İYİ PARTİ" ~ "iyi",
      TRUE ~ first_party
    ),
    second_party = case_when(
      second_party == "CHP" ~ "chp",
      second_party == "AK PARTİ" ~ "akp",
      second_party == "MHP" ~ "mhp",
      second_party == "İYİ PARTİ" ~ "iyi",
      TRUE ~ second_party
    )
  ) %>%
  ungroup()

# 查看结果
result

代码说明

  • arrange(desc(votes), .by_group = TRUE):确保每个城市内按票数从高到低排序
  • slice(1:2):直接提取每个城市的前2名,比top_n更直观控制数量
  • pivot_wider:将每个排名对应的政党和票数转为单独的列
  • case_when:将政党名称转换为期望的小写缩写格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:25:35