如何删除前导“0”。在数字R变量中 [英] How to remove leading "0." in a numeric R variable
问题描述
-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屋!