将R中的数字arg矢量化为format()
我想用另一个向量中指定的动态数字来格式化数字向量<代码>格式仅使用将R中的数字arg矢量化为format(),r,R,我想用另一个向量中指定的动态数字来格式化数字向量格式仅使用数字向量的第一个元素。有没有办法将其矢量化 例如: format(c(0.15, 0.43), digits=c(1, 2)) # [1] "0.1" "0.4" # Expected: c("0.1", "0.43") 您可以使用sprintf() 这是基于?sprintf sprintf("%2$.*1$g", c(1, 2), c(0.15, 0.43)) # [1] "0.1" "0.43" n <- 1:6 ##
数字
向量的第一个元素。有没有办法将其矢量化
例如:
format(c(0.15, 0.43), digits=c(1, 2))
# [1] "0.1" "0.4"
# Expected: c("0.1", "0.43")
您可以使用sprintf()
这是基于?sprintf
sprintf("%2$.*1$g", c(1, 2), c(0.15, 0.43))
# [1] "0.1" "0.43"
n <- 1:6
## Asterisk and argument re-use, 'e' example reiterated:
sprintf("e with %1$2d digits = %2$.*1$g", n, exp(1))
# [1] "e with 1 digits = 3" "e with 2 digits = 2.7"
# [3] "e with 3 digits = 2.72" "e with 4 digits = 2.718"
# [5] "e with 5 digits = 2.7183" "e with 6 digits = 2.71828"
每个akrun的n
mapply(format, c(0.15, 0.43), digits=c(1,2))
#[1] "0.1" "0.43"
虽然这可能比Richard Scriven的sprintf
建议慢,但对我来说效果更好,因为我使用的是格式的其他部分,不太适合sprintf
,比如千位分隔符。你可以使用mapply
即mapply(格式,c(0.15,0.43),数字=c(1,2))#[1]“0.1”“0.43”
但我不确定这是否是您想要的。