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

在R中重塑数据表:将列转为行以生成规范展示表格

R语言数据表重塑解决方案

方法1:使用tidyverse工具链

先加载依赖包,按步骤处理数据:

library(tidyverse)

# 1. 去除重复行(每个group仅保留唯一记录)
dt_unique <- dt %>% distinct(group, .keep_all = TRUE)

# 2. 将yes/no列转为长格式,同时转换数值类型
dt_long <- dt_unique %>%
  pivot_longer(cols = c(yes, no), names_to = "Response", values_to = "Value") %>%
  mutate(Value = as.numeric(Value))

# 3. 单独处理perc列,生成"per"对应的行
perc_rows <- dt_unique %>%
  mutate(Response = "per", Value = perc) %>%
  select(group, Response, Value)

# 4. 合并数据并转成目标宽格式,按指定顺序排列行
final_dt <- bind_rows(dt_long, perc_rows) %>%
  pivot_wider(names_from = group, values_from = Value) %>%
  arrange(match(Response, c("yes", "no", "per")))

# 查看结果
final_dt

输出结果:

# A tibble: 3 × 10
  Response Group 1 Group 2 Group 3 Group 4 Group 5 Group 6 Group 7 Group 8 Group 9
  <chr>      <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>
1 yes            9       9       9      12      12      12      10      10      10
2 no             9       9       9       6       6       6       8       8       8
3 per           0.5     0.5     0.5    0.67    0.67    0.67    0.56    0.56    0.56

方法2:使用data.table工具链

如果习惯用data.table(原数据为data.table格式),可使用以下代码:

library(data.table)

# 1. 去重,保留每个group的唯一记录
dt_unique <- unique(dt, by = "group")

# 2. 将yes/no列转为长格式,转换数值类型
dt_long <- melt(dt_unique, id.vars = "group", measure.vars = c("yes", "no"),
                variable.name = "Response", value.name = "Value")
dt_long[, Value := as.numeric(Value)]

# 3. 生成perc对应的行
perc_rows <- dt_unique[, .(group, Response = "per", Value = perc)]

# 4. 合并数据并转成宽格式,调整行顺序
final_dt <- dcast(rbind(dt_long, perc_rows), Response ~ group, value.var = "Value")
final_dt <- final_dt[match(c("yes", "no", "per"), Response)]

# 查看结果
final_dt

输出结果:

Response Group 1 Group 2 Group 3 Group 4 Group 5 Group 6 Group 7 Group 8 Group 9
1:      yes       9       9       9      12      12      12      10      10      10
2:       no       9       9       9       6       6       6       8       8       8
3:      per     0.5     0.5     0.5    0.67    0.67    0.67    0.56    0.56    0.56

关键步骤说明

  • 去重:原数据中每个group的数值重复3次,保留唯一行可避免后续处理产生冗余;
  • 长格式转换:将yes/no列转为行,对应Response和Value字段,统一数据结构;
  • perc行处理:单独提取百分比列转为"per"行,确保和yes/no行结构一致;
  • 宽格式转换:将group字段转为列名,最后按yes/no/per的顺序排列行,匹配目标格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:18:30