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

R语言长数据框转宽表时如何将x变量取值纳入列名标识

解决方法

基础reshape函数实现

你原来的代码仅将t作为时间维度,x变量仍作为单独分组存在,因此无法将x的取值合并到列名中。只需把x和t同时设置为timevar参数的取值,再调整列名即可:

# 长转宽处理
wide_df <- reshape(df, idvar = "g", timevar = c("x", "t"), direction = "wide", sep = ".")
# 移除列名前缀的y.
colnames(wide_df) <- sub("^y\\.", "", colnames(wide_df))
# 可选操作:将g列设为行名,和你给出的示例格式完全匹配
rownames(wide_df) <- wide_df$g
wide_df <- wide_df[,-1]

tidyr::pivot_wider实现(更简洁直观)

使用tidyverse生态的pivot_wider函数可以一步得到符合要求的结果:

library(tidyr)
wide_df <- df %>% 
  pivot_wider(
    id_cols = g,
    names_from = c(x, t),
    values_from = y,
    names_sep = "."
  )
# 可选操作:将g列设为行名
rownames(wide_df) <- wide_df$g
wide_df <- wide_df[,-1]

两种方法最终输出的结果和你期望的格式完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:15:05