2

Anybody knows how to set thousands separator in R?
I would like to get in output sth like that:

123 425 231

or

123.425.231

instead of:

123425231

Thanks.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
max04
  • 5,315
  • 3
  • 13
  • 21
  • At least don't use points, they are the standard way in R for indicating decimals. – Jaap Oct 18 '15 at 06:47
  • find this post for more answers for your question, http://stackoverflow.com/questions/3838774/comma-separator-for-numbers-in-r – Ven Yao Oct 18 '15 at 08:18

2 Answers2

8

You can try this:

x <- 123456789101112 
formatC(x, format="f", big.mark = ",", digits=0)
#[1] "123,456,789,101,112"

Of course you can change the entry of "big.mark" as you like, e.g., replace it with a whitespace.

RHertel
  • 23,412
  • 5
  • 38
  • 64
  • Thank You. Its simple and convenient solution but it doesnt worksfor large numbers (with >11 digits). – max04 Oct 18 '15 at 09:59
  • @MariuszLiksza You can try by changing to `format='f'` – akrun Oct 18 '15 at 10:02
  • @MariuszLiksza Please check the edited version. For large integers it is better to convert to floating points with `format="f"`, as I originally posted and as suggested by @akrun. – RHertel Oct 18 '15 at 10:16
  • If you want to use 64 bit integers you need to use other packages. There are several such packages, and the loss of accuracy with integers larger than 16 digits is neither related to your question nor to the answer (the accuracy is lost anyway, with or without the separators). – RHertel Oct 18 '15 at 10:39
  • Thanks but sometimes R output wrong number in the end. For instance: > `formatC(123456789101114354 , format="f", big.mark = ",",digits=0)` output > `352` in the end. – max04 Oct 18 '15 at 10:39
  • @RHertel Thank You! I didnt know that. – max04 Oct 18 '15 at 10:43
5

Through regex,

gsub("(?!^)(?=(?:\\d{3})+$)", ".", '53332', perl=T)
# [1] "53.332"
gsub("(?!^)(?=(?:\\d{3})+$)", ".", '533382', perl=T)
# [1] "533.382"
gsub("(?!^)(?=(?:\\d{3})+$)", ".", '5333829', perl=T)
# [1] "5.333.829"
gsub("(?!^)(?=(?:\\d{3})+$)", ",", '5333829', perl=T)
# [1] "5,333,829"
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274