Prou Prou Tyu
Prou Prou Tyu

Reputation: 419

Add a dot after a number in R

I have the following list c(1.23,1,0.9) which Shows in the console[1] 1.23 1 0.9 , I would like to transform it to: [1] 1.23,1.,.9 . As you can see the first numebr remains the same but 1 become 1. and 0.9 become .9.

Is there is an elegant way to have this Format ?

Regards

Upvotes: 0

Views: 974

Answers (2)

lmo
lmo

Reputation: 38500

Here is a method with sprintf and gsub:

gsub("0", "", sprintf("%.2f", x))
[1] "1.23" "1."   ".9"

To add the commas you could place this in a paste function.

paste(gsub("0", "", sprintf("%.2f", x)), collapse=",")
[1] "1.23,1.,.9"

Upvotes: 0

Emmanuel-Lin
Emmanuel-Lin

Reputation: 1943

This a matter of printing, or representations.

What you might want to do is transform it as a character:

res <- as.character(c(1.23,1,0.9))

And then use regexp:

res <- gsub("^0", "", res) # delete leading 0s
res[!grepl("\\.", res)] <- paste0(res[!grepl("\\.", res)], ".") # Add a "." at the end where there are no 0s

And the result is:

res
[1] "1.23" "1."   ".9" 

Upvotes: 5

Related Questions