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

如何将DataFrame的单元格跨行跨列拼接为指定格式字符串

解决方案

方法一:基础R原生实现

无需额外安装包,用基础R函数就能完成需求:

# 加载数据框
dat <- structure(list(V1 = c(2022, 2023, 2024, 2025), V2 = c(31L, 26L, 40L, 17L)), row.names = c(NA, -4L), class = "data.frame")

# 1. 逐行拼接每行的V1和V2,格式为"年份: 数值"
row_content <- apply(dat, 1, function(row) paste0(row["V1"], ": ", row["V2"]))
# 2. 把所有行的拼接结果用"; "连接成单个字符串
s <- paste(row_content, collapse = "; ")

执行后输出结果:

> s
[1] "2022: 31; 2023: 26; 2024: 40; 2025: 17"

方法二:tidyverse/dplyr实现

如果日常使用tidyverse工具集,写法更直观:

library(dplyr)

# 加载数据框
dat <- structure(list(V1 = c(2022, 2023, 2024, 2025), V2 = c(31L, 26L, 40L, 17L)), row.names = c(NA, -4L), class = "data.frame")

s <- dat %>%
  # 生成每行的拼接字符串
  mutate(row_str = paste0(V1, ": ", V2)) %>%
  # 提取所有行的拼接结果
  pull(row_str) %>%
  # 合并成单个目标字符串
  paste(collapse = "; ")

同样能得到符合要求的结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 02:41:09