问题描述
这是一个数据集 - 它有一个数量的估计值,以及该估计值的 95% 置信区间的下限和上限的两个单元格:
d <- data.frame(estimate = c(380.3),low_95 = c(281.6),high_95 = c(405.7))
我想将这些单元格中的每一个连接成一个新字符串——只是我想添加一些字符元素,以便结果是一个如下所示的单元格:
380.3 (281.6,405.7)
我根据 this post 在 unite
中摆弄过 dplyr
,但我什至无法将数字与下划线连在一起,更不用说插入空格、括号了,和一个逗号。
解决方法
我们可以在sprintf
中使用base R
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,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)"