添加项目名称和相应的平均值以在 R 中打印消息

Adding item names and corresponding mean values to print message in R

我有一个数据框newdat1我正在获取其中的项目(列)意味着如下:

means<-sapply(newdat1,mean)
> print(means)
      i3       i2       i1 
1.290640 1.330049 1.231527

我正在尝试获取一条打印消息,其中给出了项目名称和相应的平均值,如下所示: "i3 1.29064039408867, i2 1.33004926108374, i1 1.23152709359606 are the means in this analysis" 然而,我所能得到的只有:

> sprintf("%s are the means in this analysis", paste(means, collapse = ", "))
[1] "1.29064039408867, 1.33004926108374, 1.23152709359606 are the means in this analysis"

所以基本上我是在尝试将项目名称添加到打印消息中。有什么想法吗?谢谢!

不使用names,它不会打印出来。所以,我们在 paste 步骤中添加它,它应该按预期打印。

 sprintf("%s are the means in this analysis",
            paste(names(means), means, collapse = ", "))
 #[1] "i3 1.29064, i2 1.330049, i1 1.231527 are the means in this analysis"