假设我正在使用R中的一些代码,如下所示:
library(data.table)
dt <- data.table(x=c(1:200),y=rnorm(200))
probs <- c(0.1, 0.25, 0.5, 0.75, 0.9)
quantiles <- quantile(dt$y, prob=probs)
我想生成一个名为labels
的新变量(数组或序列),它包含分位数及其相应值的格式化字符串. 让我们假设quantiles
打印出这个:
> quantiles
10% 25% 50% 75% 90%
-1.2097339 -0.6195308 -0.0155171 0.7417443 1.2982685
如何通过编程从值quantiles
生成labels
,以便在打印输出labels
时,它会发出如下序列数组:
> labels
[1] "10% at -1.20" "25% at -0.61" "50% at -0.01" "75% at 0.74" "90% at 1.29"
那么,你如何将所有这些连接在一起,以产生labels
个? 假设我们有probs
,我们可以通过压缩probs
和quantiles
的值来简化这个过程.
我的目标是使用labels
用ggplot
包来标记密度函数的x轴,其中我想优雅地将分位数及其值一起标记(think about something like this).
Zipping the Data Together
我已经看到,我可以使用内置函数names
以编程方式判断分位数:
> names(quantiles)
[1] "10%" "25%" "50%" "75%" "90%"
我还了解到,我可以使用as.vector
以编程方式提取分位数的值:
> as.vector(quantiles)
[1] -1.2097339 -0.6195308 -0.0155171 0.7417443 1.2982685
但我没见过zipping these two things together à la Python岁的人.
String Formatting
然后需要格式中各个分位数值的小数精度,这需要类似于对每个值使用sprintf("%.2f", ...)
的内容.
序列中每个格式化的值可能都会产生sprintf("%s at %.2f", q, v)
.
我断断续续地使用R已经有20年了,但我从来没有能够深刻地保留其中的技能.我面临的主要问题是这两个数据的管道和人体工程学连接在一起.通过其他研究,我发现了类似于paste0(names(quantiles), '=', unlist(quantiles), collapse=' at ')
的结果,但这并没有产生正确的结果:
> paste0(names(quantiles), '=', unlist(quantiles), collapse=' at ')
[1] "10%=-1.20973393089285 at 25%=-0.619530792386393 at 50%=-0.0155171014275248 at 75%=0.741744347748158 at 90%=1.29826846939529"
它产生一个单一的字符串(而不是一个序列),并且分位数的精度太高.