Home > Back-end >  How to format output in R containing both integers and real numbers?
How to format output in R containing both integers and real numbers?

Time:07-25

The output of my code is following:

print(c(ax,bx,cx,dx))
>[1] 232.0000 2.0000 0.6578 1.2356

where in all the cases, the first two numbers are integers, and the rest are real. What should I include in the print statement, such that the output is:

>[1] 232 2 0.6578 1.2356

I know this must be very simple, but somehow I could not figure this out. Thanks for your help :)

CodePudding user response:

Thanks to @user2554330, for mentioning using noquote like this:

ax = 232.0000 
bx = 2.0000 
cx = 0.6578 
dx = 1.2356
print(noquote(as.character(c(ax,bx,cx,dx))))
#> [1] 232    2      0.6578 1.2356

Created on 2022-07-24 by the reprex package (v2.0.1)

You could use as.character to remove the trailing zeros like this:

ax = 232.0000 
bx = 2.0000 
cx = 0.6578 
dx = 1.2356
print(as.character(c(ax,bx,cx,dx)))
#> [1] "232"    "2"      "0.6578" "1.2356"

Created on 2022-07-24 by the reprex package (v2.0.1)

CodePudding user response:

While I like noquote, replacing all trailing zeros will have the same effect:

sub("0 $", "", as.character(c(ax,bx,cx,dx)))
[1] "232"    "2"      "0.6578" "1.2356"
  • Related