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

在R中使用pivot_wider失败,如何实现指定宽格式数据输出?

如何用tidyr实现指定的宽表转换?

问题描述

尝试使用代码pivot_wider(DATA, names_from = Year, values_from = c(Type, Language))将R语言中的DATA转换为目标输出Desired_output但未成功,需要实现将每个年份对应的Type和Language合并为一个字符串,以年份作为列名的宽表格式。

示例数据

library(tidyverse)

DATA <- read.table(header=TRUE, text="
ID District       Type Year Language
1 GreshamBarlow   5F  1617   Spanish
1 GreshamBarlow   5F  1718   Spanish
2 JeffersonCounty 5F  1617   English
2 JeffersonCounty 5F  1718   English")

Desired_output <- read.table(header=TRUE, text="
ID District        1617             1718 
1  GreshamBarlow   5F_Spanish       5F_Spanish
2  JeffersonCounty 5F_English       5F_English")

解决方案

核心思路是先将Type和Language合并为单个字段,再执行pivot_wider转换,具体代码如下:

# 合并Type与Language字段
DATA_processed <- DATA %>%
  mutate(combined = str_c(Type, Language, sep = "_"))

# 转换为目标宽表格式
result <- DATA_processed %>%
  pivot_wider(
    id_cols = c(ID, District),  # 保留的标识列
    names_from = Year,          # 作为列名的字段
    values_from = combined      # 填充列值的字段
  )

# 输出结果
result

执行后得到的结果与Desired_output一致:

# A tibble: 2 × 4
     ID District        `1617`      `1718`     
  <int> <chr>           <chr>       <chr>      
1     1 GreshamBarlow   5F_Spanish  5F_Spanish 
2     2 JeffersonCounty 5F_English  5F_English

说明

原代码直接使用values_from = c(Type, Language)会生成如Type_1617、Language_1617这类拆分的列,无法满足合并字段的需求。先合并字段再转换,就能让每个年份列对应合并后的字符串值,匹配目标输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:13:24