【问题标题】:Print a integer vector as decimal number将整数向量打印为十进制数
【发布时间】:2011-12-04 12:13:25
【问题描述】:

如果你声明一个混合了十进制和整数值的数字向量并打印它,它们都将转换为十进制数。

s <- c(0, 1.1, 2, 3)
print(s)
[1] 0.0 1.1 2.0 3.0

但如果你使用 cat 而不是 print,每个数字都会根据其类型进行格式化。

cat(s, sep=" ")
0 1.1 2 3 

如何使用 cat 打印数字向量,但又像 print 那样将值转换为十进制数?

最好的

【问题讨论】:

    标签: r


    【解决方案1】:

    例如:

    > cat(sprintf("%.01f", s))
    0.0 1.1 2.0 3.0
    

    【讨论】:

      【解决方案2】:

      你可以使用格式:

      cat(format(s,digits=2))
      

      【讨论】:

      • 这将不再适用于整数向量,而是使用cat(format(s, nsmall = 2))
      猜你喜欢
      • 1970-01-01
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      相关资源
      最近更新 更多