
[英]Looking for a way to loop through columns of a dataset to calculate multiple confidence intervals (to be inserted to a new column)
[英]Is there any way to join two columns with a minus sign and covered by round backets to show confidence intervals in one column
Values = c(2,3,4,5.4,6,1)
upper_limit = c(1.1,2,3,3.2,4,5)
lower_limit = c(3.4 ,2.4,2.2,3.3,3.3,5.2)
df =data.frame(Values,lower_limit,upper_limit)
df
我想创建一个新的第 4 列,其上限和下限都为 (LU),如下所示
Upper and Lower limit
(3.4-1.1)
(2.4-2.0)
(2.2-3.0)
(3.3-3.2)
(3.3-4.0)
(5.2-5.0)
我们可以使用sprintf
df$lab <- with(df, sprintf('(%.2f-%.2f)', lower_limit, upper_limit))
df$lab
#[1] "(3.40-1.10)" "(2.40-2.00)" "(2.20-3.00)" "(3.30-3.20)" "(3.30-4.00)" "(5.20-5.00)"
使用paste0
:
df$lab <- with(df, paste0("(", lower_limit, "-", upper_limit, ")"))
df
Values lower_limit upper_limit lab
1 2.0 3.4 1.1 (3.4-1.1)
2 3.0 2.4 2.0 (2.4-2)
3 4.0 2.2 3.0 (2.2-3)
4 5.4 3.3 3.2 (3.3-3.2)
5 6.0 3.3 4.0 (3.3-4)
6 1.0 5.2 5.0 (5.2-5)
要像示例中那样格式化小数,请在将值从数字转换为字符时使用format
:
df$lab <- with(df, paste0("(",
format(lower_limit, digits = 2), "-",
format(upper_limit, digits = 2),
")"
)
)
df
Values lower_limit upper_limit lab
1 2.0 3.4 1.1 (3.4-1.1)
2 3.0 2.4 2.0 (2.4-2.0)
3 4.0 2.2 3.0 (2.2-3.0)
4 5.4 3.3 3.2 (3.3-3.2)
5 6.0 3.3 4.0 (3.3-4.0)
6 1.0 5.2 5.0 (5.2-5.0)
library(dplyr)
df %>%
mutate(lab = paste0("(",format(lower_limit,2), "-", format(upper_limit,2),")"))
Values lower_limit upper_limit lab
1 2.0 3.4 1.1 (3.4-1.1)
2 3.0 2.4 2.0 (2.4-2.0)
3 4.0 2.2 3.0 (2.2-3.0)
4 5.4 3.3 3.2 (3.3-3.2)
5 6.0 3.3 4.0 (3.3-4.0)
6 1.0 5.2 5.0 (5.2-5.0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.