0

I'm trying to use regex to add ".0" to the end of numbers that do not already have a decimal.

For a simple reproducible example:

library(tidyverse)
library(stargazer)

mtcars %>% 
  head(3) %>% 
  select(mpg, hp) %>% 
  stargazer(summary = FALSE, digits = 1, type = "text")

Gives output that looks like this:

#> 
#> ======================
#>               mpg  hp 
#> ----------------------
#> Mazda RX4      21  110
#> Mazda RX4 Wag  21  110
#> Datsun 710   22.8   93 
#> ----------------------

I would like to add ".0" to all of the numbers that do not have a decimal place already. So my desired output would be the html version of this:

#> ======================
#>               mpg  hp 
#> ----------------------
#> Mazda RX4     21.0  110.0
#> Mazda RX4 Wag 21.0  110.0
#> Datsun 710    22.8   93.0 
#> ----------------------

The table above was in text format for readability, but my real problem is in HTML, so I'm looking at a problem like:

library(tidyverse)
library(stargazer)

mtcars %>% 
  head(3) %>% 
  select(mpg, hp) %>% 
  stargazer(summary = FALSE, digits = 1, type = "html")


#> <table style="text-align:center"><tr><td colspan="3" style="border-bottom: 1px solid black"></td></tr><tr><td style="text-align:left"></td><td>mpg</td><td>hp</td></tr>
#> <tr><td colspan="3" style="border-bottom: 1px solid black"></td></tr><tr><td style="text-align:left">Mazda RX4</td><td>21</td><td>110</td></tr>
#> <tr><td style="text-align:left">Mazda RX4 Wag</td><td>21</td><td>110</td></tr>
#> <tr><td style="text-align:left">Datsun 710</td><td>22.8</td><td>93</td></tr>
#> <tr><td colspan="3" style="border-bottom: 1px solid black"></td></tr></table>

Can anyone help with a gsub, regex, or stringr solution to this?

This previous question has answers for the latex solution, but I'm after a HTML solution.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Jeremy K.
  • 1,710
  • 14
  • 35

1 Answers1

2

We can use sprintf

library(dplyr)
library(stargazer)
mtcars %>% 
  head(3) %>% 
  select(mpg, hp) %>%
  mutate(across(everything(), sprintf, fmt = '%0.1f')) %>%
  stargazer(summary = FALSE, digits = 1, type = 'text')

-output

#============
#  mpg   hp  
#------------
#1 21.0 110.0
#2 21.0 110.0
#3 22.8 93.0 
#------------
akrun
  • 874,273
  • 37
  • 540
  • 662