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

时间:2015-07-28 20:22:26

标签: r mean

我有一个数据框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"

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

1 个答案:

答案 0 :(得分:2)

不使用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"