如何删除前导“0”。在数字R变量中 [英] How to remove leading "0." in a numeric R variable

查看:370
本文介绍了如何删除前导“0”。在数字R变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何才能简单地改变一个数字R变量(保持数字),使
-0.34变成简单的-34?

解决方案

只有当你输出一个数值时,你必须选择一个具体的表示形式(即如何格式化数字)。您不能将数值变量从-0.34更改为-34;然而,当你输出表达式 e 时,你可以选择它应该格式化。我不知道任何内置的方式来离开领先的0,但你总是可以手动删除它:

 > sub(^( - ?)0。,\\1。,sprintf(%。2f,-0.34))
[1]-.34

您可以为了方便而定义一个函数,例如

<$ p $ (%(2f,val))},这样,


How can one concisely change a numeric R variable (keeping it numeric) so that, e.g., "-0.34" becomes simply "-.34"?

解决方案

Only when you output a numeric value do you have to choose a concrete representation (i.e., how the number should be formatted). You cannot change a numeric variable from "-0.34" to "-.34"; both are representations for the same number.

However, when you output an expression e, you can choose how it should be formatted. I don't know of any build-in way to leave off the leading "0", but you could always just remove it manually:

> sub("^(-?)0.", "\\1.", sprintf("%.2f", -0.34))
[1] "-.34"

You can define a function for convenience, e.g.,

numformat <- function(val) { sub("^(-?)0.", "\\1.", sprintf("%.2f", val)) }

这篇关于如何删除前导“0”。在数字R变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆