开发者

add commas into number for output

开发者 https://www.devze.com 2022-12-08 14:06 出处:网络
I\'m outputting a dataframe to html via xtable. I wa开发者_如何学Pythonnt to add commas to numbers in a couple columns of the table. I figured before I did my own paste hack I\'d check if there is a b

I'm outputting a dataframe to html via xtable. I wa开发者_如何学Pythonnt to add commas to numbers in a couple columns of the table. I figured before I did my own paste hack I'd check if there is a built in way to do this.


You might want to consider transforming the column using formatC

> formatC(1:10 * 100000, format="d", big.mark=",")
 [1] "100,000"   "200,000"   "300,000"   "400,000"   "500,000"   "600,000"  
 [7] "700,000"   "800,000"   "900,000"   "1,000,000"


Huge thanks to Jonathan Chang for his answer. formatC looks to be an extremely useful function. This inspired me to read the documentation for it, wherein I found prettyNum, which turned out to be a pretty elegant solution to a similar problem I was having. Here's a minimum viable example of what I did to add commas to numbers in a data frame named enrollment.summary.

xtable(prettyNum(enrollment.summary,big.mark=","))


You can also try using the function argument 'format.args'

  ## Demonstration of additional formatC() arguments.
  print(fm1.table, format.args = list(big.mark = "'", decimal.mark = ","))

from here

https://cran.rstudio.com/web/packages/xtable/xtable.pdf


Here is a late answer, but you could also use scales::comma_format as follows:

library(scales)
values <- c(1000000.789, 8888.23)
comma_format(digits = 12)(values)
## [1] "1,000,000.789" "8,888.230"

For just integer values, you can just use comma:

library(scales)
int_vals <- c(1234, 5678)
comma(int_vals)
## [1] "1,234" "5,678"


to format some summaries from dplyr, here is boilerplate code:

df %>%
    summarise(mu=mean(big_values),
              min=min(big_values),
              max=max(big_values)) %>%
    mutate_each(funs(prettyNum(., big.mark=",")))
0

精彩评论

暂无评论...
验证码 换一张
取 消