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

R语言如何按客户列值转置表格,保留idMarket与idSection为行维度

你要的长表转宽表操作可以通过R的tidyverse套件快速实现,具体代码如下:

1. 构造测试数据(实际使用时替换为你自己的数据集即可)

# 加载依赖包,未安装的话先运行 install.packages("tidyverse")
library(tidyverse)

# 示例原始数据
df <- tibble(
  idMarket = c(2,2,3,3),
  idSection = c(99,99,67,67),
  idClient = c(23,56,23,56),
  Score = c(100,25,56,50),
  `%` = c("1", "0,2", "0,5", "0,3")
)

2. 核心转换代码

df_result <- df %>%
  pivot_wider(
    id_cols = c(idMarket, idSection),
    names_from = idClient,
    values_from = c(Score, `%`),
    names_glue = "{ifelse(.value == 'Score', 'Client', '%')}{idClient}"
  )

运行后得到的df_result就是你要的目标表格结构。
如果你习惯用基础R函数,可以用reshape实现:

df_result_base <- reshape(
  df,
  idvar = c("idMarket", "idSection"),
  timevar = "idClient",
  direction = "wide"
)
# 调整列名符合要求
colnames(df_result_base) <- gsub("^Score\\.", "Client", colnames(df_result_base))
colnames(df_result_base) <- gsub("^%\\.", "%", colnames(df_result_base))

注意:如果你的%列需要做数值计算,建议先把列值里的逗号替换为点再转成数值类型,仅做展示的话保持现有字符格式即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:06:04