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

如何转换R语言DataFrame:复制行并拆分某列值至两行

解决R语言DataFrame行拆分问题

问题说明

现有如下DataFrame:

df1 <- data.frame(ID = c("A","B","F","G","B","B","A","G","G","F","A","A","A","B","F"),
                 code = c(1,2,2,3,3,1,2,2,1,1,3,2,2,1,1),
                 value =  c(100,50,100,100,50,50,100,100,100,50,50,100,100,50,100))

需要将每一行拆分为两行,满足:

  • ID列重复保留
  • code列一行维持原值,另一行在原值基础上加1
  • value列一行维持原值,另一行取原值的一半

目标转换结果如下:

df1 <- data.frame(ID = c("A", "A","B","B","F","F","G","G","B","B","B","B","A","A","G","G","G","G","F","F","A","A","A","A","A","A","B","B","F", "F"),
                 code = c(1,2,2,3,2,3,3,4,3,4,1,2,2,3,2,3,1,2,1,2,3,4,2,3,2,3,1,2,1,2),
                 value =  c(100,50,50,25,100,50,100,50,50,25,50,25,100,50,100,50,100,50,50,25,50,25,100,50,100,50,50,25,100,50))

解决方案

方法1:使用tidyverse工具包

借助dplyr和tidyr的组合,通过生成列表再展开的方式实现:

library(tidyverse)

df_result <- df1 %>%
  mutate(
    # 为每个code生成原值+原值+1的列表
    code = map(code, ~c(.x, .x + 1)),
    # 为每个value生成原值+原值/2的列表
    value = map(value, ~c(.x, .x / 2))
  ) %>%
  # 将列表列展开为多行
  unnest_longer(c(code, value))

# 查看转换结果
print(df_result)

方法2:使用Base R

无需额外安装包,通过行索引复制和列修改实现:

# 复制每一行两次,生成两倍行数的DataFrame
df_result <- df1[rep(seq_len(nrow(df1)), each = 2), ]

# 对所有偶数行(原行的第二份)修改code和value
df_result$code[seq(2, nrow(df_result), 2)] <- df_result$code[seq(2, nrow(df_result), 2)] + 1
df_result$value[seq(2, nrow(df_result), 2)] <- df_result$value[seq(2, nrow(df_result), 2)] / 2

# 重置行名
rownames(df_result) <- NULL

# 查看转换结果
print(df_result)

两种方法都能得到符合要求的结果,可根据个人习惯选择使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 18:13:28