R when using paste or paste 0 0.0

This is a simple question, but it starts to annoy me that I can’t find a solution ....

I would like to be able to support 0.0 when using it as 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" 
+4
source share
3 answers

You can use sprintf() :

 paste0("x", sprintf("%.1f", y), "x") 
+12
source

There is also formatC :

 paste0("x", formatC(y, digits = 1, format = "f"), "x") 
+9
source

There is also format and drop0trailing

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

And if you really want to replace 0 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 less typical)

 paste0('x',gsub("^0$", "0.0", as.character(y)),'x') 
+7
source

Source: https://habr.com/ru/post/1432003/


All Articles