Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将R中的数字arg矢量化为format()_R - Fatal编程技术网

将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”
但我不确定这是否是您想要的。