R语言设置数值输出(保留至小数点后位数和保留有效数字)

本文详细介绍了R语言中四种控制数字输出的方法:使用options(digits)调整输出精度,round(x,n)进行四舍五入,signif(y,n)指定有效数字,以及sprintf(fmt,...)格式化字符串输出。通过实例演示了各种函数的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


在R语言中,数字的输出默认为7位:

> a = 0.1234567890   #10位
> a
[1] 0.1234568

注:输出结果四舍五入。


1 options(digits)函数

通过options(digits)函数设置输出长度,当digits = 3时:

> options(digits = 3)	
> a = 0.1234567890	#10位
> a
[1] 0.123

digits = 10时:

> options(digits = 10)
> a = 0.1234567890   #10位
> a
[1] 0.123456789

digits最大取22,超过22会报错:

> options(digits = 3)
> options(digits = 22)
> options(digits = 23)
Error in options(digits = 23) : 
  invalid 'digits' parameter, allowed 0...22

输出的结果只保留了9位,末尾的0被省略。


2 round(x, n)函数

round(x, n)函数中,x为数字,n为小数点后保留的位数,设置n = 4时:

> a = 0.1234567890   #10位
> round(a, 4)
[1] 0.1235
> a = 1.234567890   #小数点后9位
> round(a, 4)
[1] 1.2346

注:输出结果四舍五入。
当设置n = 10时:

> a = 0.1234567890   #10位
> round(a, 10)
[1] 0.123456789

输出的结果只保留了9位,末尾的0被省略。

当小数点后的0的位数超过n时,输出的结果为0:

> a = 0.0001234567890   #13位
> round(a, 3)
[1] 0
> a = 0.0001234567890   #13位
> round(a, 4)
[1] 1e-04

3 signif(y, n)函数

signif(x, n)函数中,x为数字,n为有效数字的个数 ,当n = 4时:

> a = 1.234567890   #小数点后9位
> signif(a, 4)
[1] 1.235
> a = 0.000001234567890   #小数点后15位
> signif(a, 4)
[1] 1.235e-06

n = 10时:

> a = 1.234567890   #小数点后9位
> signif(a, 10)
[1] 1.23456789

此时数字末尾的0依旧被省略。


4 sprintf(fmt, …)函数

> a = 0.1234567890   #小数点后10位
> sprintf("%0.4f", a)
[1] "0.1235"
> a = 0.1234567890   #小数点后10位
> sprintf("%0.10f", a)
[1] "0.1234567890"

通过sprintf(fmt, ...)函数可以保留末尾的0。

当输入为整数时,位数不够会在输入值前面补0:

> a = 12456789
> sprintf("%03d", a)
[1] "12456789"
> a = 12
> sprintf("%03d", a)
[1] "012"

欢迎大家批评指正。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

A-Chin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值