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

R语言如何转换数据框格式,将Variable列转为列、V1/V2/V3转为行

R数据格式转换实现方案

你需要先将V1/V2/V3三个值列转为长格式生成County标识列,再将Variable列的取值扩展为新列即可得到预期结果,完整代码如下:

library(tidyverse)

# 原始数据
df = data.frame(Variable=rep(c("f10","f21","f32"),each=5), 
                Year=rep(paste("20",11:15,sep=""),3),             
                V1=sample(1:5,15,replace=T),V2=sample(5:10,15,replace=T),V3=sample(5:10,15,replace=T))

# 转换代码
res <- df %>%
  # 把V开头的列转为长格式,生成County列存储变量名,value列存储对应数值
  pivot_longer(cols = starts_with("V"), names_to = "County", values_to = "value") %>%
  # 把Variable列的取值转为新列,取值对应上述value列
  pivot_wider(names_from = Variable, values_from = value)

转换后的数据结构与要求完全一致,因为原始数据中V1/V2/V3是随机生成的,最终数值会和示例输出略有差异,但列结构和行排列逻辑完全匹配。


原代码问题说明

你之前直接调用pivot_wider的写法会为每个V列和Variable取值的组合生成单独列(如V1_f10/V1_f21等),无法生成合并的County标识列,因此不符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:24:00