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
相关产品推荐
相关产品推荐

