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

如何基于值列表扩展tibble中的行并替换coor列数据

方案1:dplyr 1.1.0+ 最简实现

用reframe()直接替换coor列即可,其余列会自动按行数重复:

library(tidyverse)

# 构造原始数据
df <- tibble(
  first = "first",
  coor = "ALL",
  second = "second"
)

coor_list <- c("ESP", "FRA", "GER")

# 核心代码
df_res <- df %>%
  reframe(
    first,
    coor = coor_list,
    second
  )

方案2:兼容旧版dplyr的实现

配合tidyr::crossing()做笛卡尔积实现扩展:

df_res <- df %>%
  select(-coor) %>%
  crossing(coor = coor_list) %>%
  relocate(coor, .after = first) # 调整列顺序和原始结构匹配

方案3:Base R 实现

不需要加载任何包,直接重复行后替换列值:

# 重复原始行N次,N为coor列表长度
df_res <- df[rep(1, length(coor_list)), ]
# 替换coor列值
df_res$coor <- coor_list

内容的提问来源于stack exchange,提问作者Robin Lindström

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:45:07