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

R语言如何将dataframe转换为列名与数值混合的文本字符串?

R语言实现方案

以下两种方法均可直接生成你需要的格式化字符串,生成结果可直接复制到Excel使用。

方法1:tidyverse实现(推荐,代码简洁易读)

library(tidyverse)

# 构造数据,直接粘贴你给出的structure代码即可
df <- structure(list(Method = c("Logistic Regression", "Naive Bayes", 
"Tree", "Neural Network", "AdaBoost", "CN2 rule inducer", "kNN", 
"SVM", "SGD", "Constant"), AUC = c(0.732, 0.729, 0.678, 0.674, 
0.654, 0.651, 0.649, 0.64, 0.591, 0.5), CA = c(0.684, 0.694, 
0.694, 0.684, 0.681, 0.681, 0.66, 0.691, 0.667, 0.625), F1 = c(0.413, 
0.463, 0.429, 0.413, 0.418, 0.403, 0.372, 0.44, 0.4, 0), Precision = c(0.681, 
0.679, 0.717, 0.681, 0.66, 0.674, 0.604, 0.686, 0.615, 0), Recall = c(0.296, 
0.352, 0.306, 0.296, 0.306, 0.287, 0.269, 0.324, 0.296, 0)), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

# 生成每个模型对应的格式化字符串向量
result <- df %>%
  rowwise() %>%
  mutate(
    metrics_str = paste0(names(.)[-1], " ", c_across(-Method), collapse = ", "),
    output_str = paste0(Method, ": ", metrics_str)
  ) %>%
  pull(output_str)

# 若需要所有内容合并为同一行,执行以下代码
all_in_one <- paste(result, collapse = " ")

方法2:base R实现(无需额外安装包)

# 构造数据同上,粘贴你给出的structure代码即可
df <- structure(...)

# 获取指标列名
metric_cols <- names(df)[-1]
# 逐行处理生成字符串向量
result <- apply(df, 1, function(x) {
  metrics <- paste0(metric_cols, " ", x[-1], collapse = ", ")
  paste0(x[1], ": ", metrics)
})

# 合并为单行
all_in_one <- paste(result, collapse = " ")

补充使用技巧

生成结果后如果需要直接复制到剪贴板:

  • Windows系统执行writeClipboard(all_in_one)
  • Mac系统执行writeLines(all_in_one, pipe("pbcopy"))
    执行后直接到Excel单元格粘贴即可,无需手动选中复制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:15:04