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

在R语言中如何按变量将行数据转置为列?

多变量数据转置解决方案

问题背景

现有如下格式的数据集:

dataA=data.frame(structure(list(Season = c(2021, 2021, 2021, 2021, 2021, 2022, 
                          2022, 2022, 2022, 2022, 2023, 2023, 2023, 2023, 2023), 
               ID = c("A", "B", "C", "D", "E", "A", "B", "C", "D", "E", "A", "B", "C", "D", "E"), 
               S = c(44, 64, 65, 68, 58, 46, 48, 48, 62, 42, 49, 63, 75, 90, 55), 
               Na = c(115, 131, 153, 118, 140, 127, 108, 119, 122, 139, 136, 134, 170, 139, 178), 
               Ca = c(1.58, 2.41, 2.49, 2.25, 2.1, 1.21, 2.07, 2.66, 2.26, 1.9, 1.36, 2.18, 2.53, 2.22, 2.12)), 
               class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -15L)))

数据预览:

SeasonIDSNaCa
2021A441151.58
2021B641312.41
2021C651532.49
2021D681182.25
2021E581402.10
2022A461271.21
2022B481082.07
2022C481192.66
2022D621222.26
2022E421391.90
2023A491361.36
2023B631342.18
2023C751702.53
2023D901392.22
2023E551782.12

需要将数据按ID分组,把Season转置为列,同时保留S、Na、Ca三个变量的对应值。尝试使用reshape::cast()时出现报错:

library(reshape)
dataB= reshape::cast(dataA, ID ~ Season, value=c("S","Na", "Ca"))

报错信息:

Error in data.frame(data[, c(variables), drop = FALSE], result = data$value) : 
  arguments imply differing number of rows: 15, 0
In addition: Warning message:
In names(data) == value :
  longer object length is not a multiple of shorter object length

可行解决方案

方法1:使用tidyverse的pivot_wider

tidyverse生态中的pivot_wider函数专门用于宽表转换,支持多变量同时转置,语法直观:

library(tidyverse)

dataB <- dataA %>%
  pivot_wider(
    id_cols = ID,          # 作为分组主键的列
    names_from = Season,   # 需要转置为列名的变量
    values_from = c(S, Na, Ca)  # 需要保留值的多变量
  )

转换后的结果格式:

IDS_2021S_2022S_2023Na_2021Na_2022Na_2023Ca_2021Ca_2022Ca_2023
A4446491151271361.581.211.36
B6448631311081342.412.072.18
C6548751531191702.492.662.53
D6862901181221392.252.262.22
E5842551401391782.101.902.12

方法2:使用data.table的dcast

如果数据集规模极大,data.table的dcast函数处理速度更快,内存效率更高:

library(data.table)

# 将data.frame转换为data.table格式
setDT(dataA)

dataB <- dcast(
  dataA,
  ID ~ Season,
  value.var = c("S", "Na", "Ca")  # 指定需要转置的多变量
)

该方法得到的结果与pivot_wider完全一致,列名格式为变量名_年份,满足转置需求。

内容的提问来源于Stack Exchange,提问作者J.K Kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:34:53