r keeping 0.0 when using paste or paste0
Asked Answered
I

3

8

This is a simple question but it is starting to annoy me that I cant find a solution....

I would like to be able to keep the 0.0 when using it as an output when using paste or paste0 so if i have the following:

y <- c(-1.5,-1.0,-0.5,0.0,0.5,1.0,1.5)
> y
[1] -1.5 -1.0 -0.5  0.0  0.5  1.0  1.5
paste0("x",y,"x")

I get:

[1] "x-1.5x" "x-1x"   "x-0.5x" "x0x"    "x0.5x"  "x1x"    "x1.5x" 

but want:

[1] "x-1.5x" "x-1.0x"   "x-0.5x" "x0.0x"    "x0.5x"  "x1.0x"    "x1.5x" 
Implied answered 3/9, 2012 at 6:41 Comment(3)
Do you want only 0.0 not 1.0 and -1.0Soviet
@mnel, good question. I didn't notice that in the output.Dripstone
apologies I wanted 1.0 and -1.0 as well... but the below answers have solved my problem so thanks!Implied
D
16

You can use sprintf():

paste0("x", sprintf("%.1f", y), "x")
Dripstone answered 3/9, 2012 at 6:47 Comment(0)
C
11

There's also formatC:

paste0("x", formatC(y, digits = 1, format = "f"), "x")
Cobra answered 3/9, 2012 at 7:2 Comment(0)
S
9

There is also format and drop0trailing

paste0('x',format(y,drop0Trailing = F),'x')

And, if you really want only 0 replaced with 0.0, not (1.0 or -1.0) then

paste0('x',gsub(x = gsub(x = format(y, drop0trailing = T),'0$', '0.0'),' ',''),'x')
## [1] "x-1.5x" "x-1x"   "x-0.5x" "x0.0x"  "x0.5x"  "x1x"    "x1.5x" 

Or, as @mrdwab suggested (and is less typying)

paste0('x',gsub("^0$", "0.0", as.character(y)),'x')
Soviet answered 3/9, 2012 at 6:56 Comment(2)
My gsub was a little different: gsub("^0$", "0.0", as.character(y)).Dripstone
Much cleaner! - added to my answerSoviet

© 2022 - 2024 — McMap. All rights reserved.