R打印不带引号的数字数据

R printing numeric data without quotes

我如何确保数字总是打印在小数点后一位数字且没有任何引号?我想要 a+b 打印 8.0,a1+a2 打印 4.2。 请注意我不需要任何引号。 我试过 format() 但它没有给出我要找的东西

> a=3
> b=5
> a+b
[1] 8
> a1=2.22
> a2=2
> a1+a2
[1] 4.22


> format(a+b,nsmall=1)
[1] "8.0"
> format(a1+a2,nsmall=1)
[1] "4.22"

您可以使用 cat 函数来避免对格式返回的字符串调用 print

cat(format(a, nsmall=1), sep="\n")

print.default 使用 quote = FALSE 参数(结合您的 format())。您可以使用 formatdigits 参数来获取小数点后最多一位数。或者你可以 round.

print(format(a + b, nsmall = 1), quote = FALSE)
# [1] 8.0

## using digits

print(format(a1 + a2, nsmall = 1, digits = 1), quote = FALSE)
# [1] 4.2
print(format(1001.12321, nsmall = 1, digits = 1), quote = FALSE) 
# [1] 1001.1

## using round

print(format(round(1001.12321, 1), nsmall = 1), quote = FALSE)
# [1] 1001.1
print(format(round(a1 + a2, 1), nsmall = 1), quote = FALSE)
# [1] 4.2