在 R 中,在插入一些文本元素时将数字列连接成一个字符串

In R, concatenate numeric columns into a string while inserting some text elements

这是一个数据集 - 它有一个数量的估计值,以及该估计值 95% 置信区间上下限的两个单元格:

d <- data.frame(estimate = c(380.3),
                low_95 = c(281.6),
                high_95 = c(405.7))

我想将这些单元格中的每一个连接成一个新字符串——只是我想添加一些字符元素,以便结果是一个看起来像这样的单元格:

380.3 (281.6, 405.7)

我在 dplyr 中基于 this post 摆弄过 unite,但我什至无法让数字与下划线粘在一起,更不用说插入空格了,括号和逗号。

我们可以在base R

中使用sprintf
with(d, sprintf('%.1f (%.1f, %.1f)', estimate, low_95, high_95))
#[1] "380.3 (281.6, 405.7)"

或者不一一指定参数,使用do.call

do.call(sprintf, c(fmt = '%.1f (%.1f, %.1f)', d))
#[1] "380.3 (281.6, 405.7)"

或者另一种选择是 glue

library(dplyr)
library(glue)
d %>% 
  glue_data("{estimate} ({low_95}, {high_95})")
#380.3 (281.6, 405.7)

您可以使用基本 R 包中的 paste0 命令在 R 中连接字符串。例如:

result <- paste0(d$estimate, " (", d$low_95, ", ", d$high_95, ")")
print(result)

[1] "380.3 (281.6, 405.7)"